[leetcode]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.

Subscribe to see which companies asked this question

根据题目要求,首先想到了判断一串字符串是否为合法字符串的方法。思路是:采用栈的方法。每次将'('左括号入栈,遇到')'右括号时,如果栈为空表示无法匹配,则为不合法的字符串,否则弹出一个左括号。到最后判断是栈是否为空,不为空则表示是不合法的。

判断字符串是否是合法的函数如下:

public boolean isValid(String s){
	if(s==null||s.length()<2)return false;
	int len=s.length();
	if(len%2!=0)return false;
	Stack<Character> stack=new Stack<Character>();
	for(int i=0;i<s.length();i++){
		if(s.charAt(i)=='(') stack.push('(');
		else{
			if(stack.isEmpty())return false;
			else stack.pop();
		}
	}
	if(stack.isEmpty())return true;
	return false;
}


根据以上思路,可以维护一个数组,用来存储字符串中的某些位是否是合法的括号,即是否被匹配,然后顺序扫描数据,得到最长的连续为true的即可。算法复杂度为O(n).

本题目的解法代码如下:

public int longestValidParentheses(String s) {
        
	if(s==null||s.length()<2)return 0;
	int len=s.length();
	Stack<Character> stack=new Stack<Character>();
	Stack<Integer> stackNum=new Stack<Integer>();
	boolean isValid[]=new boolean[len];
	for(int i=0;i<len;i++) isValid[i]=false;
	for(int i=0;i<len;i++){
		if(s.charAt(i)=='('){
			stack.push('(');
			stackNum.push(i);
		}
		else{
			if(!stack.isEmpty()){
				stack.pop();
				int k=stackNum.pop();
				isValid[i]=true;
				isValid[k]=true;
			}
		}
	}
	int result=0;
	int max=0;
	for(int i=0;i<len;i++){
		if(isValid[i]){
			result++;
			while(i+1<len&&isValid[i+1]){
				result++;
				i++;
			}
		}else{
			if(result>max)max=result;
			result=0;
		}
		if(result>max)max=result;
	}
	return max;
    }





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值