您的位置:首页 > 其它

LeetCode | Longest Valid Parentheses(最长有效的括号匹配)

2014-08-10 00:13 483 查看
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》是一样的,利用一个栈来维护。但要处理栈为空时遇到的是右括号的情况,直接忽略就好。

上面说的不正确!

当输入为()(()()的时候,返回应该是4,但程序却返回了6!单纯的被题目中的例子误导,没有考虑所有情况!

正确的解法是维护一个栈,里面放的不是单纯的字符,放的是'('的位置。

当匹配左括号后(也就是栈中有元素且当前是右括号),先退出栈,然后算坐标差值!才能是距离,比如((()),得到第二个右括号时为4-0。

但是会带来一个问题,如果退出完,就造成无法去计算差值!

首先放入-1代表匹配失效,当程序匹配失效时,就更新栈底,为新的坐标值。

代码如下:

class Solution {
public:
int longestValidParentheses(string str)
{
int n = str.size();
int result = 0;

stack<int> S;
S.push(-1);
for(int i = 0;i < n;i++){
if(str[i] == '('){  //为左括号,入栈
S.push(i);
}
else{               //为右括号
if(S.size()>1){ //当栈的元素多于一个的时候才能出栈
S.pop();
int temp = S.top();
if(i-temp > result)
result = i-temp;
}else{          //栈元素为1个,代表有效字符出栈完毕,且更新的为')'右括号的位置!
S.pop();
S.push(i);
}
}
}

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