[LeetCode] 32. Longest Valid Parentheses

[LeetCode] 32. Longest Valid Parentheses

问题描述

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

思路 – dp

dp[i]表示以第i个字符为结尾的最长合法字串的长度。
if s[i] == ‘(’: dp[i] = 0;
if s[i] == ‘)’:
如果dp[i-1]的长度之前的那个字符是’(’,则当前的’)‘正好可以凑一对,dp[i] = dp[i-1] + 2; 同时,如果’('之前也是一个合法的串,也要把那部分加上,如:(()) (()()),当验证了(()())是一个合法的情况时,还要考虑(())这部分。所以dp[i] += dp[i-dp[i-1]-2];
否则dp[i]=0;

状态转移方程

状态转移方程

代码

class Solution {
public:
  int longestValidParentheses(string s) {
    vector<int> dp(s.length(), 0);
    int result = 0;
    for (auto i = 1; i < s.length(); ++i) {
      if (s[i] == '(') continue;
       
      if (i-dp[i-1]-1 >= 0 && s[i-dp[i-1]-1] == '(') {
        dp[i] = dp[i-1] + 2;
        if (i-dp[i-1]-2 >= 0) dp[i] += dp[i-dp[i-1]-2];
      }
      result = max(result, dp[i]);
    }
    
    return result;
  }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值