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/官方的解决方案,确实比我好。

点赞