leetcode 使用栈方法和动态规划解决[32] 最长有效括号 C++

/*
 * @lc app=leetcode.cn id=32 lang=cpp
 *
 * [32] 最长有效括号
 *
 * https://leetcode-cn.com/problems/longest-valid-parentheses/description/
 *
 * algorithms
 * Hard (35.41%)
 * Likes:    1396
 * Dislikes: 0
 * Total Accepted:    173.1K
 * Total Submissions: 488.8K
 * Testcase Example:  '"(()"'
 *
 * 给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
 * 
 * 
 * 
 * 
 * 
 * 示例 1:
 * 
 * 
 * 输入:s = "(()"
 * 输出:2
 * 解释:最长有效括号子串是 "()"
 * 
 * 
 * 示例 2:
 * 
 * 
 * 输入:s = ")()())"
 * 输出:4
 * 解释:最长有效括号子串是 "()()"
 * 
 * 
 * 示例 3:
 * 
 * 
 * 输入:s = ""
 * 输出:0
 * 
 * 
 * 
 * 
 * 提示:
 * 
 * 
 * 0 
 * s[i] 为 '(' 或 ')'
 * 
 * 
 * 
 * 
 */

// @lc code=start
class Solution {
public:
    int longestValidParentheses(string s) {
        // 方法一: 通过动态规划
        // dp[i]表示以i结尾的最长有效括号长度;
        int n = s.size();
        if(n < 2)
            return 0;
        vector<int> dp(n,0);
        int res = 0;
        for(int i = 1;i<n;i++)
        {
            if(s[i] == ')')
            {
                int pre = i - dp[i-1] -1;
                if (pre >= 0 and s[pre] == '(')
                {
                    dp[i] = dp[i-1]+2;
                    // 处理独立的括号对的情形 类似()()、()(())
                    if (pre > 0) 
                    {
                        dp[i] += dp[pre-1];
                    }
                    res = max(res,dp[i]);
                }
            }
        }
        return res;
        // 方法二:通过栈的思路
        // stack<int> st;
        // int res = 0;
        // int tmp = 0;
        // bool is_continue = false;
        // for(int i = 0;i<s.size();i++)
        // {
        //     if(!st.empty())
        //     {
        //         if(s[st.top()] == '(' and s[i] == ')')
        //         {
        //             st.pop();     
        //         }
        //         else 
        //         {
        //             st.push(i);
        //         }
                
        //     }
        //     else
        //     {
        //         st.push(i);
        //     }
        // }
        // int end = s.size();
        // while(!st.empty())
        // {
        //     res = max(end - st.top()-1,res);
        //     end = st.top();
        //     st.pop();
        // }
        // res = max(end ,res);


        // return res;

    }
};
// @lc code=end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

samoyan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值