[Leetcode] Longest Valid Parentheses

Longest Valid ParenthesesMar 1 '125700 / 20657

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.

之前大摩面试时,问到了这题,当时愚昧了。

一开始,写错了。

后来,想了个N^2的方法。 T_T。

不过好歹这次一次AC :)

struct A {
    A(char cc, int vv=0) : c(cc), v(vv) {}
    char c;
    int v;
};
class Solution {
public:
    
    int longestValidParentheses(string s) {
        int len = s.size();
        if (len == 0) return 0;
        stack<A> st;
        st.push(A(s[0]));
        int cnt = 0;
        for (int i = 1; i < len; i++) {
            cnt = 0;
            if (s[i] == '(') st.push(A(s[i]));
            else {
                while (!st.empty() && st.top().c == '#') {
                    cnt += st.top().v;
                    st.pop();
                }
                
                if (!st.empty() && st.top().c == '(') {
                    cnt += 2;
                    st.pop();
                    st.push(A('#', cnt));
                }
                else {
                    // top().c == '#'
                    if (cnt > 0) st.push(A('#',cnt));
                    st.push(A(')'));
                }
            }
        }
        
        cnt = 0;
        int mx = 0;
        while (!st.empty()) {
            if (st.top().c == '#') {
                cnt += st.top().v;
                if (mx < cnt) mx = cnt;
            } else {
                cnt = 0;
            }
            st.pop();
        }
        return mx;
    }
};
class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size();
        if (n == 0) return 0;
        int i = 0;
        stack<pair<char, int> > st;
        st.push(make_pair('#', 0));
        st.push(make_pair(s[i++], 0));
        while (!st.empty() && i < n) {
            if (s[i] == '(') st.push(make_pair(s[i++], 0));
            else {
                i++;
                int cnt = 0;
                while (st.top().first == '.') cnt += st.top().second, st.pop();
                if (st.top().first == '(') {
                    st.pop();
                    st.push(make_pair('.', cnt + 1));
                }
                else {
                    if (cnt > 0) st.push(make_pair('.', cnt));
                    st.push(make_pair(')', 0));
                }
            }
        }
        int res = 0;
        while (st.top().first != '#') {
            int cnt = 0;
            while (st.top().first == '.') cnt += st.top().second, st.pop();
            res = max(res, cnt);
            while (st.top().first == '(' || st.top().first == ')') st.pop();
        }
        return res*2;
    }
};

猜你喜欢

转载自cozilla.iteye.com/blog/1927189
今日推荐