LeetCode Longest Valid Parentheses
LeetCode Longest Valid Parentheses
Original question
Find the length of the longest valid substring that only contains "(" and. Valid means that the parentheses in the substring can be correctly matched.
Note:
Note that empty strings
Example:
Input: s = "()"
Output: 2
Input: s = ") ()"
Output: 4
Solutions
Dynamic Planning is adopted. dp [I] indicates the maximum length at the end of the substring with I. The final result is the maximum value in dp. If it is not a Null String, dp [0] = 0, because a bracket cannot match correctly. The recursive relationship is:
) ( ) ( ( ) ) )0 1 2 3 4 5 6 7
Check the matching of the first brace in the current brace. For example, the best match ending with 6 before 7 is 3-6. Check whether the brackets before 3 match with 7, if it does not match, it does not change. The best match ending with 5 before 6 is 4-5. When 3 and 6 match, dp [I] + 2. In addition, if the dp value of the parentheses before the left parentheses matching the current parentheses should also be added, because the current parentheses are added and those parentheses are also connected. For example, after 3 and 6 match, 1 and 2 should also be added to the best match ending with 6.
AC Source Code
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ if not s: return 0 length = len(s) dp = [0 for __ 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)if __name__ == "__main__": assert Solution().longestValidParentheses("(()))())(") == 4 assert Solution().longestValidParentheses("(()") == 2 assert Solution().longestValidParentheses(")()())") == 4