zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    Python之datetime模块
    PEP8规范 Python
    redis操作命令
    Django之Cookie、Session和自定义分页
    登录之验证码相关实现
    装饰器进阶
    js中的cookie使用和vue-cookie的使用
    vue-cli的安装使用
    Django之进阶相关操作
    PyMySQL模块的使用
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854188.html
Copyright © 2011-2022 走看看