32. Longest Valid Parentheses

本文探讨了如何找出包含'('和')'字符的字符串中最长的有效括号子串长度。通过动态规划的方法,详细解释了算法实现过程,并提供了一个C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

分析:

对于字符串中每一个元素,只有两种取值,'('和')'
所以可分以下情况
  • S[i]等于'('时,因为S[i-1]肯定不能与S[i]组合成有效的一对括号,可以不用考虑
  • S[i]等于')'时,有两种情况
  1. s[i-1]等于'(',则dp[i]=dp[i-2]+2
  2. s[i-1]等于')',则dp[i]=dp[i-1]+2+dp[i-dp[i-1]-2]
因为题意中的Valid指连续的括号才算有效,所以需取最大值

代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值