Leetcode--Dynamic Programming(python)

5.Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"

最長迴文字符串,標準動態規劃,找到轉移點“如果一個字符串是迴文串,那麼在它左右分別加上一個相同的字符,那麼它一定還是一個迴文串”;dp關鍵是兩部分,一個是base case,一個轉移方陣;base case有兩種情況,單個字符和兩個相鄰相同字符;使用dp[i][j]表示從i位置到j位置的字符串是否是迴文。

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        
        if len(s) <= 1:
            return s
        
        dp = [[False for i in range(len(s))] for j in range(len(s))]
        res = ""
        
        for i in range(len(s)-1, -1, -1):
            for j in range(i, len(s)):
                if i == j:
                    dp[i][j] = True
                elif abs(i-j) == 1 and s[i] == s[j]:
                    dp[i][j] = True
                elif s[i] == s[j] and dp[i+1][j-1] == True:
                    dp[i][j] = True
                    
                tmp = s[i:j+1]
                if dp[i][j] == True and len(tmp) > len(res):
                    res = tmp
                    
        return res
        
        

32. Longest Valid Parentheses

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

用一維數組來表示,不要用二維的布爾矩陣表示
) ( ) ( ( ) ) )
0 1 2 3 4 5 6 7
看當前括號的前一個括號的匹配情況,例如在7之前以6結尾的的最佳匹配是3-6,看3之前的括號和7是否匹配,不匹配則沒有變化;而6之前以5結尾的最佳匹配是4-5,此時3和6匹配,則dp[i]+2。此外,如果與當前括號匹配的左括號之前的括號的dp值也應該加進來,因爲由於添加了當前的括號,那些括號也被連接起來了。例如3和6匹配後,1和2也應該被加到以6結尾的最佳匹配中。

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        if len(s) <=1:
            return 0
        
        length = len(s)
        dp = [0 for i in range(length)]
        for i in range(1, length):
            if s[i] == ")":
                j = i - 1 - dp[i - 1]
                if j >= 0 and s[j] == "(":
                    dp[i] = dp[i - 1] + 2
                    if j - 1 >= 0:
                        dp[i] += dp[j - 1]
        return max(dp)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章