leetcode 32. Longest Valid Parentheses

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:

Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”

用dp,f[i] 表示以 i 为结尾的字符串得到的最长有效括号的长度,则 s[i]==') 时,分两种情况:

  1. s[i-1]=='( ,则 f[i]=f[i-2]+2
  2. s[i-1]==')s[i-f[i-1]-1]=='(',则 f[i]=f[i-1]+f[i-f[i-1]-2]+2

时间和空间复杂度都是 O(n)O(n)

class Solution {
public:
    int f[100005];
    int longestValidParentheses(string s) {
        int n=s.length();
        int res=0;
        for(int i=1;i<n;i++){
            if(s[i]==')'){
                if(s[i-1]=='(')
                    f[i]=(i>=2?f[i-2]:0)+2;
                else if(i-f[i-1]>0&&s[i-f[i-1]-1]=='(')
                    f[i]=f[i-1]+((i-f[i-1])>=2?f[i-f[i-1]-2]:0)+2;
                res=max(res,f[i]);
            }
        }
        return res;
    }
};

还可以用栈做:

class Solution {
public:
    int longestValidParentheses(string s) {
        int n=s.length();
        int res=0;
        stack<int> st;
        st.push(-1);
        for(int i=0;i<n;i++){
            if(s[i]=='(')st.push(i);
            else{
                st.pop();
                if(st.empty())st.push(i);
                else res=max(res,i-st.top());
            }
        }
        return res;
    }
};

最后一种解法很神奇,先从左往右扫描一次,再从右往左扫描一次:

class Solution {
public:
    int longestValidParentheses(string s) {
        int n=s.length();
        int res=0;
        int a=0,b=0;
        for(int i=0;i<n;i++){
            if(s[i]=='(')a++;
            else b++;
            if(a==b)res=max(res,2*a);
            else if(a<b)a=b=0;
        }
        a=b=0;
        for(int i=n-1;i>=0;i--){
            if(s[i]=='(')a++;
            else b++;
            if(a==b)res=max(res,2*a);
            else if(a>b)a=b=0;
        }
        return res;
    }
};
posted @ 2020-07-23 11:06  winechord  阅读(104)  评论(0编辑  收藏  举报