leetcode(32) Longest Valid Parentheses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/specialshoot/article/details/50755601

原题链接:https://leetcode.com/problems/longest-valid-parentheses/

找到最多数量的()匹配

思路:遇到左括号将左括号标号入栈,遇到右括号的情况下分两种情况:

1.如果前面的左括号栈为空,说明前面已经没有左括号了,此时右括号无效,需要重新定位start数值

2.如果前面的左括号栈不为空,这时要把这个左括号下标出栈,若为此时栈为空则max为Math.max(max,i-start+1),i-start+1即为中间所有字符数量.若不为空,则max为Math.max(max,i-stack.peek()),i-stack.peek()代表此时右括号到栈顶左括号之间的合法括号个数.

由此得到以下代码(主函数进行测试):

package leetcode;

import java.util.LinkedList;

public class LongestValidParentheses {
	// https://leetcode.com/problems/longest-valid-parentheses/

	public static int longestValidParentheses(String s) {
		if (s == null || s.length() == 0){
			return 0;
		}
		LinkedList<Integer> stack = new LinkedList<Integer>();
		int start = 0;
		int max = 0;
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				stack.push(i);
				System.out.println("push -> "+i);
			} else {
				if (stack.isEmpty()) {
					//如果栈为空,说明前面已经没有匹配,start重新赋值起始位置
					start = i + 1;
				} else {
					stack.pop();
					max = stack.isEmpty() ? Math.max(max, i - start + 1) : Math.max(max, i - stack.peek());
					if(!stack.isEmpty())
						System.out.println("i-stack.peek() -> "+ (i - stack.peek()));
				}
			}
		}
		return max;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(longestValidParentheses("()(()") + "");
	}

}


猜你喜欢

转载自blog.csdn.net/specialshoot/article/details/50755601