Longest Valid Parentheses - Leetcode

本文介绍了一种求解字符串中最长有效括号子串长度的方法。通过动态规划记录每个位置的有效括号长度,并更新最大长度,实现高效查找。

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

public class Solution {
    public int longestValidParentheses(String s) {
        int[] f = new int[s.length()];
        int ret = 0;
        for(int i=1; i<s.length(); i++){
            if(s.charAt(i)==')' && i-f[i-1]-1>=0 && s.charAt(i-f[i-1]-1)=='('){
                f[i]=f[i-1]+2;
                if(i-f[i]>0)
                    f[i] += f[i-f[i]];
            }
            ret = Math.max(ret, f[i]);    
        }
        return ret;
    }
}


思路:想了一下,遍历string 的时候每一次有效长度都可能变化,上一个的结果影响下一个的结果,但是不决定下一个的结果。因此,需要记录上一个位置的结果,在此基础上决定当前的值,知道走到string最后。这里面还有一点,如果中途括号顺序被破坏,那么需要重新计算。计算的值比较之前的最大值。

如果当前值的符号无效, f[n] = f[n-1]; 如果当前值的符号有效,f(

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值