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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章