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;
}
巧妙地利用栈,保留下标,然后根据条件判断,逐步计算出结果。
分支条件有三到四个,也挺容易出错的题目。
- classSolution{
- public:
- intlongestValidParentheses(strings)
- {
- intn=s.length();
- stack<int>stk;
- intlongestLen=0;
- for(inti=0;i<n;i++)
- {
- if(s[i]=='(')stk.push(i);
- else
- {
- if(stk.empty())
- {
- stk.push(i);
- }
- else
- {
- if(s[stk.top()]!='(')
- stk.push(i);
- else
- {
- stk.pop();
- //居然会漏了max写成maxLen=(maxLen,i+1)
- if(stk.empty())longestLen=max(longestLen,i+1);
- elselongestLen=max(longestLen,i-stk.top());
- }
- }
- }
- }
- returnlongestLen;
- }
- };