LeetCode 31 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.

思路:其实这个题是道细节题,很多地方容易出错。本人使用的两个栈,一个栈存放String的内容,将不匹配的进栈。另一个栈存放的是string的下标,内容不匹配的下标进栈,而匹配的出栈。最后看存放下标的栈 两个数字差的最大值,注意栈中有k个数,则整个字符串有k+1,即需要做k+1次减法来求最大值。

public class Solution {
	public int longestValidParentheses(String s) {
		if (s == null || s.length() == 0 )return 0;
		
		int result = 0;
		int temp = 0;
		Stack<Character> sk = new Stack<Character>();
		Stack<Integer> stack = new Stack<Integer>();

		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				sk.push('(');
				stack.push(i);
			} else if (!sk.isEmpty() && sk.pop() == '(') {
				stack.pop();
			} else {
				stack.push(i);
				sk.clear();
			}
		}
		if (stack.isEmpty()) return s.length();

		result = s.length() - stack.peek();
		while (!stack.isEmpty()) {
			int num1 = stack.peek();
			int num2;
			stack.pop();
			if (stack.isEmpty()) {
				num2 = -1;
			} else {
				num2 = stack.peek();
			}
			temp = num1 - num2;
			if (result < temp) result = temp;
		}

		return result - 1;
	}
}

思路2:在思路1的基础上改进一点点,存放下标的栈最开始push(-1),最后再push(s.length()),假设思路1中存放下标的栈有k个数字,则思路2有有k+2个数字,不过还是只有k+1段,缩减了些代码行数。

public class Solution {
	public int longestValidParentheses(String s) {
		if (s == null || s.length() == 0) return 0;

		int result = 0;
		Stack<Character> sk = new Stack<Character>();
		Stack<Integer> stack = new Stack<Integer>();
		stack.push(-1);
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				sk.push('(');
				stack.push(i);
			} else if (!sk.isEmpty() && sk.pop() == '(') {
				stack.pop();
			} else {
				stack.push(i);
				sk.clear();
			}
		}
		
		stack.push(s.length());
		while (!stack.isEmpty()) {
			int num1 = stack.peek();
			int num2=0;
			stack.pop();
			if(!stack.isEmpty())
				num2 = stack.peek();
			result=result >(num1-num2)?result:(num1-num2);
		}

		return result - 1;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值