Longest Valid Parentheses

本文介绍了一种使用栈和动态规划方法求解最长有效括号序列的问题。通过两种不同的实现方式,展示了如何高效地找到字符串中包含的最大长度的有效括号子串。
部署运行你感兴趣的模型镜像
public class Solution {
    public int longestValidParentheses(String s) {
		// Start typing your Java solution below
		// DO NOT write main() function
		int len = s.length();
		int max = 0;
		Stack<Integer> stack = new Stack<Integer>();
		for(int i = 0; i < len; i++){
			if(s.charAt(i) == '(')
				stack.push(i);
			else{
				if(!stack.empty() && s.charAt(stack.peek()) == '('){
					stack.pop();
					if(stack.empty())
						max = Math.max(max, i + 1);
					else{
						max = Math.max(max, i - stack.peek());
					}
				}
				else
					stack.push(i);
			}
		}
		return max;
	}
}

Same idea. Using arrays instead of a stack.


public class Solution {
    public int longestValidParentheses(String s) {
		// Start typing your Java solution below
		// DO NOT write main() function
		if (s == null || s.length() == 0)
			return 0;
		int l = s.length();
		int dp[] = new int[l];
		int max = 0, j;

		for (int i = 1; i < l; i++) {
			if (s.charAt(i) == ')') {
				j = i - 1 - dp[i - 1];
				if (j >= 0 && s.charAt(j) == '(')
					dp[i] = i - j + 1 + ((j > 0) ? dp[j - 1] : 0);
			}

			if (dp[i] > max)
				max = dp[i];
		}
		return max;
	}
}


您可能感兴趣的与本文相关的镜像

HunyuanVideo-Foley

HunyuanVideo-Foley

语音合成

HunyuanVideo-Foley是由腾讯混元2025年8月28日宣布开源端到端视频音效生成模型,用户只需输入视频和文字,就能为视频匹配电影级音效

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值