您的位置:首页 > 其它

leetcode:Longest Valid Parentheses

2014-07-06 15:54 288 查看
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;//记录左括号的下标
int max_length = 0; int last_match = -1;//记录上一个")"的下标
for( int i = 0; i < s.size(); ++i){
if( s[i] == '(')
stk.push(i);
else{
if( !stk.empty()){
stk.pop();//两个括号匹配,出栈
if( !stk.empty())//如果不为空,右括号一直是跟栈顶的左括号匹配,也就是未匹配左括号中最右的括号
max_length = max( max_length, i - stk.top());//所以这里更新长度,是i-stk.top()
else//一次有效匹配结束
max_length = max( max_length, i - last_match);
}
else
last_match = i;
}
}
return max_length;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: