您的位置:首页 > 其它

LeetCode: Longest Valid Parentheses

2012-10-07 17:19 387 查看
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int nSize = s.size();
if (nSize <= 1)
return 0;

stack<int> pare;
int longest = 0;
int top = nSize;
for (int i = 0; i < nSize; ++i)
{
if (s[i] == '(')
pare.push(i);
else if(!pare.empty())
{
int tmp = pare.top();
pare.pop();
top = top < tmp ? top : tmp;
if (pare.empty())
longest = longest > i - top + 1 ? longest : i - top + 1;
else
longest = longest > i - pare.top() ? longest : i - pare.top();
}
else
top = i + 1;
}

return longest;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: