今天闲来无事又刷了几道。
Longest Valid Parentheses
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.
class Solution { public: int longestValidParentheses(string &s) { if (s == "") return 0; int cnt = 0; int totr = 0; int lastValid = -1; for (int i = 0;i < s.length();i++) { if (s[i] == ‘)‘) totr++; cnt += (s[i] == ‘(‘ ? 1:-1); if (cnt < 0) { if (i+1 < s.length()) { s = s.substr(i+1,s.length()-i-1); return max(i,longestValidParentheses(s)); } else return i; } if (cnt == 0) lastValid = i; } if (lastValid > 0) { s = s.substr(lastValid+1,s.length()-lastValid-1); for (auto& x : s) x = (x==‘(‘?‘)‘:‘(‘); reverse(s.begin(),s.end()); return max(longestValidParentheses(s),lastValid + 1); } else { for (auto& x : s) x = (x==‘(‘?‘)‘:‘(‘); reverse(s.begin(),s.end()); return longestValidParentheses(s); } } };
只能说,我想歪了。这是道简单的DP,中间还WA了很多次。
我这个神奇的做法也是醉了。
比较需要引起注意的是,递归当中,如果带着数组字符串之类的,如果没有&,很容易MLE。
标准的做法是 f[i] 表示 i 结尾最长的合法序列,
如果(结尾, 0
如果()结尾, f[i-2]+2
如果))结尾, s[i - f[i-1] - 1]==‘(‘ 的情况下 f[i-f[i-1]-2]+f[i-1]+2
时间: 2024-10-15 09:48:42