LeetCode(32)

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size(),i = 0,maxResult = 0,result = 0,t,tmax,tsum;
        if(n==0)return 0;
        stack<char>st;
        stack<int>st2;
        while(i!=n||!st.empty()){
            if(i!=n&&st.empty()){
                if(s[i]==')'){
                    maxResult = max(maxResult,result);
                    result = 0;
                    while(!st.empty()){
                        st.pop();
                    }
                }
                else if(s[i]=='('){
                    st2.push(i);
                    st.push('(');
                }
                i++;
            }
            else if(i!=n&&!st.empty()){
                if(s[i]==')'){
                    result += 2;
                    // maxResult = max(maxResult,result);
                    st2.pop();
                    st.pop();
                }
                else if(s[i]=='('){
                    st2.push(i);
                    st.push('(');
                }
                i++;
            }
            else if(i==n&&!st.empty()){
                t = n;tmax = 0;tsum = 0;
                while(!st.empty()){
                    st.pop();
                    tsum += t-st2.top()-1;
                    tmax = max(tmax,t-st2.top()-1);
                    // cout<<t<<" "<<st2.top()<<" "<<tmax<<" "<<tsum<<endl;
                    t = st2.top();
                    st2.pop();
                }
                result -= tsum;
                result = max(result,tmax);
                maxResult = max(maxResult,result);
            }
        }
        maxResult = max(maxResult,result);
        return maxResult;
    }
};

 

上一篇:广(宽)度优先搜索


下一篇:856_括号的分数