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.
思路:当碰到")"时,向左遍历找到未标记过的"(",则将这两个位置标为1,然后统计1连续出现的长度即可,时间复杂度为O(n^2)。
class Solution { public: int longestValidParentheses(string s) { int n = s.length(); if (n<1) { return 0; } bool matched[n]; memset(matched,0,sizeof(matched)); int i,j; for(i=0; i<n; ++i) { if(s[i] == ')') { j = i - 1; while(j>=0) { if(!matched[j]&&s[j]=='(') { matched[j] = true; matched[i] = true; break; } --j; } } } int co = 0; int max = INT_MIN; for(i=0; i<n; ++i) { if(matched[i]) { co++; } else { max = (max<co?co:max); co = 0; } } if (co>0) { max = (max<co?co:max); } return (max==INT_MIN?0:max); } };