LeetCode 32 Longest Valid Parentheses (C++, Python)
Given a string containing just the characters
'('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For
"(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is
")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class Solution { public: int longestValidParentheses(string s) { int left = 0; int right = 0; int maxlen = 0; for (int i = 0; i < s.length(); ++i) { if (s[i] == '(') { left ++; } else { right ++; } if (left < right) { left = 0; right = 0; } else if (left == right) { maxlen = max(maxlen, right * 2); } } left = 0; right = 0; for (int i = s.length() - 1; i >= 0; --i) { if (s[i] == '(') { left ++; } else { right ++; } if (left > right) { left = 0; right = 0; } else if (left == right) { maxlen = max(maxlen, right * 2); } } return maxlen; } }; |
Solution Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution: # @param s, a string # @return an integer def longestValidParentheses(self, s): dp = [0] * (len(s) + 1) maxlen = 0 for i in range(len(s) - 1, -1, -1): if s[i] == ')': continue j = i + 1 + dp[i + 1] if j == len(s): continue if s[j] == '(': continue dp[i] = 2 + dp[i + 1] + dp[j + 1] maxlen = max(maxlen, dp[i]) return maxlen |