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

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;
    }
};

  

posted @ 2014-10-04 21:21  zombies  阅读(203)  评论(0编辑  收藏  举报