32. Longest Valid Parentheses

本文介绍了一种高效算法,用于寻找给定字符串中最长的有效括号子串长度。通过动态规划方法,巧妙地处理了仅包含'('和')'字符的字符串,实现了对最长合法括号序列的精确计算。

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

public class Solution {
    public int longestValidParentheses(String s) {
                if(s.isEmpty())
			return 0;
//CUT all ")" at the head of a string like ")))))))))()()" -----> "()()"
		for(int i = 0 ; i < s.length(); i++)
		{
			if( s.charAt(i) != ')')
			{
				s = s.substring(i);
				break;
			}
		}
                
                /*for (int i=s.length()-1; i>=0; i--) {
                        if (s.charAt(i) != '(') {
                                s = s.substring(0,i+1);
                                break;
                        }
                }*/

		int sLength = s.length();
		int[] dp = new int[sLength];
		int maxLength = 0;
		dp[0] = 0;
			
		for(int i = 1 ; i < sLength; i++)
		{
//Valid "()" appears only if the current is ")"
			if(s.charAt(i) == ')')
			{
			    if(i - dp[i-1] - 1 >=0 && s.charAt(i - dp[i-1] - 1) == '(')
				{
//Core part1, compute the length of valid "()" formed by current ")"
					dp[i] = dp[i - 1] + 2;

//Core part2, add the adjacent valid length ahead of the current valid "()"
					if(i - dp[i - 1] - 2 >=0 )
					    dp[i] += dp[i - dp[i - 1] - 2];
					if(dp[i] > maxLength) 
				        maxLength = dp[i];
				}

//Core part3, find the next posible position to compute the next valid length
				int nextPossiblePosition = s.indexOf(')', i + 1);
				if(nextPossiblePosition == -1)
				    break;
				else
				    i = nextPossiblePosition - 1;
			}
		}
		return maxLength;
    }
}
//构思真的很巧妙,抓住了”)“的特性
//如果不是很懂,可以拿些示例数据进行调试~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值