最长连续有效括号 Longest Valid Parentheses @LeetCode

思路:用栈保存左括号(


遇到(就直接压入栈中。


遇到):要用一个变量保存第一个(的下标位置firstLeftPos

如果当前栈为空,则更新firstLeftPos,然后忽略这个)。

如果栈非空,则弹栈,取出匹配的(。如果弹栈后的栈非空则根据当前)的下标和栈顶元素计算长度;如果弹栈后的栈为空,则更具当前)的下标和firstLeftPos计算长度。


package Level4;

import java.util.Stack;

/**
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.
 */
public class S32 {

	public static void main(String[] args) {
		System.out.println(longestValidParentheses("(())"));
		System.out.println(longestValidParentheses(")("));
		System.out.println(longestValidParentheses("()()"));
		System.out.println(longestValidParentheses("(()"));
	}

	public static int longestValidParentheses(String s) {
		if(s.length() < 2){
			return 0;
		}
		Stack<Pair> stack = new Stack<Pair>();
		int curPos = 0;
		int firstLeftPos = 0;		// 存放第一个 ( 的下标位置
		int max = 0;
		while(curPos < s.length()){
			char c = s.charAt(curPos);
			if(c == '('){
				stack.push(new Pair(c, curPos));
			}else{		// c == ')'
				if(!stack.isEmpty()){		// 栈非空
					stack.pop();	// 把对应的 ( 弹出
					if(!stack.isEmpty()){	// 弹栈后,栈内仍有元素
						max = Math.max(max, curPos-stack.peek().index);
					}else{	// 弹栈后,栈空了
						max = Math.max(max, curPos-firstLeftPos+1);
					}
				}else{	// 栈空,又遇到 ), 更新都一个(的下标位置
					firstLeftPos = curPos + 1;
				}
			}
			curPos++;	// 更新当前遍历string的下标位置
		}
		return max;
	}
	
	// 构建一个Pair,同时存放字符和其对应下标
	public static class Pair{
		char c;
		int index;
		public Pair(char c_, int index_){
			c = c_;
			index = index_;
		}
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值