32. Longest Valid Parentheses (Stack; DP)

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.

法I:把所有invalid的括号位置都标记出来,比较invalid之间的长度哪段最长

class Solution {
public:
    int longestValidParentheses(string s) {
        vector<int> invalidPos;
        invalidPos.push_back(-1);
        invalidPos.push_back(s.length());
        stack<int> lParenPos;
        int len = 0, ret = 0;
        
        for(int i = 0; i < s.length(); i++){
            if(s[i]=='('){
                lParenPos.push(i);
            }
            else{ //right parenthese
                if(lParenPos.empty()){
                    invalidPos.push_back(i);
                }
                else{
                    lParenPos.pop();
                }
            }
        }
        
        while(!lParenPos.empty()){
            invalidPos.push_back(lParenPos.top());
            lParenPos.pop();
        }
        
        sort(invalidPos.begin(), invalidPos.end());
        for(int i = 1; i < invalidPos.size(); i++){
            len = invalidPos[i]-invalidPos[i-1]-1;
            if(len > ret) ret = len;
        }
        
        return ret;
    }
};

法II:动态规划

class Solution {
public:
    int longestValidParentheses(string s) {
        if(s.empty()) return 0;
        stack<int> leftStack;
        int ret = 0;
        int currentMax = 0;
        int leftPos;
        vector<int> dp(s.length()+1,0); //currentMax无法检测到连续valid的情况,eg: ()(), 所以需要动态规划记录i位置之前连续多少个valid。
       
        for(int i = 0; i <s.length(); i++){
            if(s[i]==')'){
                if(leftStack.empty()){
                    currentMax = 0;
                }
                else
                {
                    leftPos = leftStack.top();
                    leftStack.pop();
                    currentMax = i-leftPos+1 + dp[leftPos];
                    dp[i+1] = currentMax;
                    ret = max(ret,currentMax);
                }
            }
            else{
                leftStack.push(i); //push the index of '('
            }
        }
        return ret;
    }
};
原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854188.html