Longest Valid Parentheses

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

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
大概意思是找寻最长有效括号的长度, 这是我的源代码
public int longestValidParentheses(String s) {
        List<Integer> point = new LinkedList<Integer>();

		int begin = 0, end = 0;
		int oldBegin = 0, oldEnd = -2;
		int arrzyIndex = -1;
		
		for (int i = 0; i < s.length();) {

			if (s.charAt(i) == '(' && i + 1 < s.length() && s.charAt(i + 1) == ')') {
				begin = i;
				end = i + 1;
				
				while(begin - 1 >= 0 && s.charAt(begin - 1) == '(' && end + 1 < s.length() && s.charAt(end + 1) == ')') {
					begin--; end++;
				}
				
				if(oldEnd + 1 == begin) {
					begin = oldBegin;
					
					while(begin - 1 >= 0 && s.charAt(begin - 1) == '(' && end + 1 < s.length() && s.charAt(end + 1) == ')') {
						begin--; end++;
					}
					
					while(arrzyIndex > 2 && point.get(arrzyIndex - 2) + 1 == begin) {
						begin = point.get(arrzyIndex - 3);
						while(begin - 1 >= 0 && s.charAt(begin - 1) == '(' && end + 1 < s.length() && s.charAt(end + 1) == ')') {
							begin--; end++;
						}
						point.remove(arrzyIndex);
						point.remove(arrzyIndex - 1);
						arrzyIndex -= 2;
					}
					
					point.set(arrzyIndex - 1, begin);
					point.set(arrzyIndex, end);
					
				} else {
					point.add(begin);
					point.add(end);
					arrzyIndex += 2;
				}
				
				oldBegin = begin;
				oldEnd = end;
				i = end + 1;
			} else {
				i++;
			}
		}
		
		int maxLength = -1;
		
		for(int i = 0; i < point.size(); i += 2) {
			if(point.get(i + 1) - point.get(i) > maxLength) {
				maxLength = point.get(i + 1) - point.get(i);
			}
		}
			
		return maxLength + 1;
    }

这道题我想了很久,大概4天,由于近期心事太多的原因,最终采用最开始的方案。我的方案是这样的

1. 先找出所有的() (()) ..这样的括号

2.开始合并

3. 合并的时候注意 (A B) 这样的

4. 不断的重复 2、3即可

5. 找出最大的一组即可

看了看https://leetcode.com/problems/longest-valid-parentheses/solution/官方的解决方案,确实比我好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李文区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值