您的位置:首页 > 其它

LeetCode-Longest Valid Parentheses-最长匹配括号-栈的应用

2014-10-04 21:21 477 查看
https://oj.leetcode.com/problems/longest-valid-parentheses/

这题一直没有把问题想清楚,浪费了不少时间。最终解法如下:

1)第一次遍历所有元素,用一个栈记录还没有匹配的"("括号的位置,在遇到")"括号匹配时出栈一个元素。

2)用一个bool 数组当做map,在有括号被匹配时将这之间的元素置为true.

3)最后遍历一遍bool数组,求出最大连续的true个数即可。这种求最大连续个数的问题可以只用一个count,在false时不断清零即可。

class Solution {
public:
int n,m;
int longestValidParentheses(string s) {
n=s.length();
stack <int> st;
vector <bool> flags(n,false);
for (int i=0;i<n;i++){
if (s[i]=='('){
st.push(i);
continue;
}
if (s[i]==')'){
if (!st.empty()){
int l=st.top();
for (int j=l;j<i+1;j++){flags[j]=true;}
st.pop();
}
}
}
int count=0;
int res=0;
for (int i=0;i<n;i++){
if (flags[i]){
count++;
res=max(res,count);
}
else{
count=0;
}
}
return res;
}
};


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