LeetCode 32 Longest Valid Parentheses

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.

方法一:stack和dp。Runtime: 21 ms beats 65.63% of java submissions.

	public int longestValidParentheses(String s) {
		int max = 0, start;
		Stack<Integer> stack = new Stack();
		if (!s.contains(")")) return 0;
		int[] a = new int[s.length()];//a[i]记录longestValidParentheses(s.substring(0,i+1))
		char[] c = s.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '(') stack.push(i);
			else if (!stack.empty()) {
				start = stack.pop();
				a[i] = i - start + 1;
				if (start > 1) a[i] += a[start - 1];
				max = Math.max(max, a[i]);
			}
		}
		return max;
	}

方法二:当S[i] = ')'的时候,‘)’才会和前面的'('匹配。只有在当S[i] = ')'的时候,DP[i]才可能不为0,如果S[i] = '(',DP[i]没有被赋值,依然为初始化数据0。

下面代码中,比较难理解的是int j = i - 1 - DP[i - 1];    如果DP[i - 1]=0,那么S[i-1]和其前面的字符没有进行匹配,此时 j = i - 1,看S[j]=S[i-1]是否为‘(’即可。

如果DP[i - 1]不等于0,那么S[i-1]和其前面的字符已经进行了匹配,结果是DP[i - 1],此时 j = i - 1- DP[i - 1],即  i - (S[i-1]和前面字符匹配的长度) -1 , S[i-1]所匹配的字符串的前一位,是否为‘(’即可。

Runtime: 16 ms  beats 97.93% of java submissions.

	public int longestValidParentheses(String s) {
		char[] S = s.toCharArray();
		int[] DP = new int[S.length];
		int max = 0;
		for(int i = 1; i < S.length; i++){
			if(S[i] == ')'){
				int j = i - 1 - DP[i - 1];
				if(j >= 0 && S[j] == '('){
					DP[i] = 2 + DP[i - 1] + (j > 0? DP[j - 1] : 0);
				}
			}
			max = Math.max(max, DP[i]);
		}
		return max;
	}


参考 https://zhengyang2015.gitbooks.io/lintcode/content/longest_valid_parentheses_32leetcode.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值