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)
{
stack<int> stk;
stk.push(-1);
int max=0;
stack<char> cstk;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(' || cstk.empty() || cstk.top()==')')
{
cstk.push(s[i]);
stk.push(i);
}
else
{
cstk.pop();
stk.pop();
if(i-stk.top()>max) max=i-stk.top();
}
}
return max;
}
};
public:
int longestValidParentheses(string s)
{
stack<int> stk;
stk.push(-1);
int max=0;
stack<char> cstk;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(' || cstk.empty() || cstk.top()==')')
{
cstk.push(s[i]);
stk.push(i);
}
else
{
cstk.pop();
stk.pop();
if(i-stk.top()>max) max=i-stk.top();
}
}
return max;
}
};

浙公网安备 33010602011771号