LeetCode Longest Valid Parentheses

本文通过动态规划(DP)方法解决寻找给定字符串中包含仅'('和')'字符的最长有效括号子串的问题。详细解释了DP数组的使用以及如何计算每个位置的有效括号子串长度。

摘要生成于 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.

题意:找到最长的合法串的长度

思路:dp的思想,用d[i]表示从第i个位置开始匹配的长度,那么对于第i个来说,如果它是右括号的话,那么这个位置就是0,如果是做括号的话,那么就要跳过第i+1匹配的最长长度的位置来到j,看位置j是不是右括号,其次还要加上位置j+1的位置的匹配长度。

class Solution {
public:
    int longestValidParentheses(string s) {
        if (s.length() == 0) return 0;

        int ans = 0;
        int *d = new int[s.length()];
        for (int i = 0; i < s.length(); i++)
            d[i] = 0;
        d[s.length() - 1] = 0;
        for (int i = s.length() - 2; i >= 0; i--) {
            if (s[i] == ')') 
                d[i] = 0;
            else {
                int j = i + 1 + d[i + 1];
                if (j < s.length() && s[j] == ')') {
                    d[i] = d[i+1] + 2;
                    if (j + 1 < s.length()) 
                        d[i] += d[j+1];
                }
            }
            ans = max(ans, d[i]);
        }

        return ans;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值