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.
每次操作栈和其他容器的时候都要注意是否为空。
这道题的计算要注意,如何才能得到当前最长valid parentheses。
int longestValidParentheses(string s)
{
stack<int> stk;
int len = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ‘(‘) stk.push(i);
else
{
if (stk.empty()) stk.push(i);
else
{
if (s[stk.top()] == ‘(‘)
{
stk.pop();
if (stk.empty()) len = max(len, i+1);
else len = max(len, i-stk.top());
}
else stk.push(i);
}
}
}
return len;
}
leetcode Longest Valid Parentheses
原文:http://blog.csdn.net/kenden23/article/details/18792193