Longest Valid Parentheses Posted on 2018-09-09 Descriptionhttps://leetcode.com/problems/longest-valid-parentheses/description/ Solution12345678910111213141516171819202122232425262728class Solution: def longestValidParentheses(self, s): """ :type s: str :rtype: int """ if s is None or len(s) == 0 or len(s) == 1: return 0 dp = [0 for i in range(len(s))] max_valid = 0 for i in range(1, len(dp)): if s[i] == '(': dp[i] = 0 else: if s[i - 1] == '(': dp[i] = (2 if i < 2 else (dp[i - 2] + 2) ) else: temp = dp[i - 1] if i - temp - 1 >= 0 and s[i - temp - 1] == '(': dp[i] = temp + 2 + (0 if i - temp - 2 < 0 else dp[i - temp - 2]) else: dp[i] = 0 max_valid = max(max_valid, dp[i]) print (dp) return max_valid