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.


刚碰到一个右括号时如果它的前一个是左括号那么就是一个有效的组合。 (( )) 第一个右括号前一个是左括号,把这一对抛去,第二个右括号的前一个还是左括号。、

可以充分应用栈的特点来实现。把括号的下标放到栈里。有效的组合下标都不会在栈里。具体策略如下:

如果是( 入栈,如果是右括号 1.栈是否为空 空入栈 2.不空 看栈顶元素是否是( 是‘(’ 弹出 这是一个有效的组合,不是‘(’ 入栈 这个右括号不会是一个有效的组合。

遍历之后判断长度,找出栈内差值最大的两个相邻元素 其之间的距离就是有效组合的最大长度


public class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stack=new Stack<Integer>();
        int n=s.length();
        int longest=0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='('){
                stack.push(i);
            }
            else{
                if(stack.isEmpty()){
                    stack.push(i);
                }
                else{
                    if(s.charAt(stack.peek())=='(')
                        stack.pop();
                    else stack.push(i);
                }
            }
        }
        if(stack.isEmpty()) longest=n;
        else{
            int a=n,b=0;
            while(!stack.isEmpty()){
                b=stack.peek();
                stack.pop();
                longest=Math.max(longest,a-b-1);
                a=b;
            }
            longest=Math.max(longest,a);
        }
        return longest;
    }
}


动态规划的解法:

dp[i]代表以i开头的有效组合的长度 (()   dp[]=0 2 0

从后往前 ,从倒数第二个开始 如果s.charAt(i)是左括号那么找在其之后的最长有效组合(这些都已经组成有效组合不用再考虑了)之后的一位是否是‘)’如果是那么dp[i]=dp[i+1]+2   即可以把有效组合的长度加2 ,加2之后需要继续考察现在这个加长之后的有效组合末尾的下一位是否还在数组索引内在的话需要把这一位对应的有效组合长度一并加上这是更长的有效组合比如  ( ( ) )  ( ) 第0个dp[1]=2 s(0)='(' s(1+2)=')' ——dp[0]=dp[1]+2=4 但dp[4]=2是可以继续连接起来的



public class Solution {
    public int longestValidParentheses(String s) {
        int dp[]=new int[s.length()];
        int j=0,max=0;
        int n=dp.length;
        for(int i=dp.length-2;i>=0;i--){
            if(s.charAt(i)=='('){
                j=i+dp[i+1]+1;
                if(j<n&&s.charAt(j)==')'){
                    dp[i]=dp[i+1]+2;
                    if(j+1<=n-2)
                        dp[i]+=dp[j+1];
                }
            }
            max=Math.max(dp[i],max);
        }
        return max;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值