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)
{
for (int i = 0; i < s.length(); ++i)
{
if (')' == s[i])
for (int j = i-1; j >= 0; j--)
{
if ('*' == s[j])
continue;
if (')' == s[j])
break;
if ('(' == s[j])
{
s[j] = '*';
s[i] = '*';
break;
}
}
}
int maxv = 0;
int cur = 0;
for (int i = 0; i < s.length(); ++i)
{
if ('*' == s[i])
cur++;
else if ('(' == s[i] || ')' == s[i])
{
maxv = max(maxv, cur);
cur = 0;
}
}
return max(maxv, cur);
}
};
拷别人用堆栈的代码:
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<int> pStack;
int lastleft=0;//keep track of the start point of the current longest valid parenthese
int longest=0;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(')
{
pStack.push(i);
}
else
{
if(!pStack.empty())
{
pStack.pop();
//now pStack.top() the previous index of the start point of the longest valid parenthese
if(!pStack.empty())
longest=max(longest,i-pStack.top());
else
longest=max(longest,i-lastleft+1);
}
else{
//mismatched ) found, the longest string must end
//update the start of the first valid parenthtes
lastleft=i+1;
}
}
}
return longest;
}
};