[LeetCode]Longest Valid Parentheses

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.

[stack解法]要点:利用stack来记录‘(’的位置。

利用stack来存储最近未匹配‘(’的位置,如果遇到’)‘就出栈,如果栈为零说明前面都是匹配的,动态更新边界点,匹配完后记录长度,找到最大值。

空间O(N),时间O(N)

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> stk; //no matching '('
        int maxlen = 0;
        int last = -1; //last ')'
        for(int i=0; i<s.length(); ++i){
            if(s[i]=='(')
                stk.push(i); 
            else {
                if(stk.empty()){
                    last = i; //previous string match
                }
                else {
                    stk.pop();
                    if(stk.empty()){
                        maxlen = max(maxlen, i-last); //start at ')' next
                    }
                    else 
                        maxlen = max(maxlen, i-stk.top()); //start at not match'(' next
                }
            }
        }
        return maxlen;
    }
};


[Dp解法]从字符串最大处开始往前扫。记录第一个未match的点,就是i+1+f(i+1)

如果未match的点和现在的点匹配,说明f(i) = f(i+1)+2;

同时还要注意一种情况,未和现在点match的后面可能还有解。比如((()))(),这种类型,此时f(i) += f(match+1)才是最后解。

class Solution {
public:
    int longestValidParentheses(string s) {
        vector<int> Dp(s.size(),0);
        int maxlen;
        if(s.size()<2)
            return 0;
        for(int i=s.size()-2; i>=0; --i){
            int match = Dp[i+1]+i+1; //the last match ')'
            if(s[i]=='(' && match<s.size()&&s[match]==')'){ //match<s.size() not the last
                Dp[i] = Dp[i+1]+2;
                if(match+1<s.size()){ //((()))(....)
                    Dp[i] += Dp[match+1];
                }
            }
            maxlen = max(Dp[i],maxlen);
        }
        return maxlen;
    }
};



你可能感兴趣的:([LeetCode]Longest Valid Parentheses)