leetcode 32 Longest Valid Parentheses

题意

给一个由'(' 和 ')'构成的字符串,求最长匹配长度

题解

class Solution {
public:
    int longestValidParentheses(string s) {
        int len = s.size();
        if (len == 0) return 0;
        stack<int> st;
        for (int i=0; i<len; i++) {
           if(s[i] == '(')
               st.push(i);
            else if(s[i] == ')') {
                if(!st.empty() && s[st.top()] == '(') {
                    st.pop();
                } else {
                    st.push(i);
                }
            }
        }
        if(st.empty()) return len;
        int mx = 0;
        int ed = len, start = 0;
        while(!st.empty()) {
            // cout << start << " ed";
            start = st.top(); st.pop();
            mx = max(mx, ed - start - 1);
            ed = start;
        }
        mx = max(mx, start);
        return mx;
    }
};
posted @ 2019-07-26 10:32  Draymonder  阅读(80)  评论(0编辑  收藏  举报