LeetCode 32 Longest Valid Parentheses 2种优雅解法

思路一 递归DP

定义子问题 : f(i) 为 以s[i] 结尾的子串的原问题,有:

  1. 如果s[i] == ‘(’:f(i) = 0
  2. 如果s[i] == ‘)’:
    1. 如果s[i - 1] == ‘(’:f(i) = f(i - 2) + 2
    2. 如果s[i - 1] == ‘)’:令 l = f(i -1), 如果s[ i - l - 1] == ‘(’,那么f(i) = f(i - 1) + 2 + f (i - l - 2),否则f(i ) = 0
def longestValidParentheses(self, s):
        # write your code here
        
        memo = [-1] * len(s)
        def help(i):
            if i < 0: return 0
            if memo[i] >= 0:
                return memo[i]
            if i == 0 or s[i] == '(':
                memo[i] = 0
            else:
                l = help(i - 1)
                if i - l - 1 >= 0 and s[i - l - 1] == '(':
                    memo[i] = l + 2 + help(i - l - 2)
                else:
                    memo[i] = 0
                    
            return memo[i]
        
        maxLen = 0      
        for i in range(len(s)):
            maxLen = max(maxLen, help(i))
        return maxLen

思路二:记录最长的“消去长度”

def longestValidParentheses(self, s):
        # write your code here
        stack = []
        ans = 0
        for i in range(len(s)):
            if len(stack) > 0 and s[stack[-1]] == '(' and s[i] == ')':
                stack.pop()
                ans = max(ans, i - -1 if len(stack) == 0 else i - stack[-1])
            else:
                stack.append(i)
        
        return ans

你可能感兴趣的:(leetcode,算法,DP)