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) { int maxlen = 0; for(int i=0; i<s.size(); ++i) { int len = maxlenbeginwith(s.substr(i) ); if(maxlen < len) maxlen = len; } return maxlen; } int maxlenbeginwith(string s) { int sum = 0,len = 0; for(int i=0; i<s.size(); ++i) { if(s[i]==')') { sum--; } else ++sum; if(sum < 0) return len; if(sum == 0) len = i+1; } return len; }*/ int longestValidParentheses(string s) { /*if(s.empty()) return 0;*/ int* dp = new int[s.size()]; memset(dp,0,sizeof(int)*s.size() ); int maxlen = 0; for(int i=1;i<s.size(); ++i) { if(s[i]==')') { if(i-dp[i-1]-1>=0 && s[i-dp[i-1]-1]=='(') { dp[i] = dp[i-1]+2; if(i-dp[i-1]-2>=0) dp[i] += dp[i-dp[i-1]-2]; if(maxlen < dp[i]) maxlen = dp[i]; } } } delete [] dp; return maxlen; } };
2.动态规划O(n),dp[i]表示以i为结尾的最长配对括号数,注意这里有括号左右顺序限制。如果是正负数个数相同问题,此方法是错误的。
扩展:求最长字串长度,字串中正负数个数相同?
1.暴力,以i为开始的。正数+1,负数-1,记录为0的位置,最后一个为0的位置-i即为该次的最长。遍历串,O(n^2)
2.O(n)怎么做?辅助数组记录从0开始到当前位置正数个数-负数个数,然后针对辅助数组分析,L[j]==L[i]说明[i+1,j]区间正数负数个数相等,j-i即为以j为结尾的长度,扫一遍辅助数组,使用hash记录L[i]和i的对,最大的即为结果。