力扣 最长有效括号(三种解法)(动态规划+栈)

在这里插入图片描述
动态规划:

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

两种用栈的解法:

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int maxn = 0,start = -1;
        for(int i = 0;i < s.size();i++){
            if(s[i] == '('){
                st.push(i);
            }
            else{
                if(st.empty()){
                    start = i;
                }
                else{
                    st.pop();
                    if(st.empty()){
                        maxn = max(maxn,i-start);
                    }
                    else{
                        maxn = max(maxn,i-st.top());
                    }
                }
            }             
        }
        return maxn;
    }
};
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        vector<bool> mark(s.length());
        for(int i = 0; i < mark.size(); i++) mark[i] = 0;
        int left = 0, len = 0, ans = 0;
        for(int i = 0; i < s.length(); i++) {
            if(s[i] == '(') st.push(i);
            else {
                // 多余的右括号是不需要的,标记
                if(st.empty()) mark[i] = 1;
                else st.pop();
            }
        }
        // 未匹配的左括号是不需要的,标记
        while(!st.empty()) {
            mark[st.top()] = 1;
            st.pop();
        }
        // 寻找标记与标记之间的最大长度
        for(int i = 0; i < s.length(); i++) {
            if(mark[i]) {
                len = 0;
                continue;
            }
            len++;
            ans = max(ans, len);
        }
        return ans;
    }
};
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值