Longest Valid Parentheses

51 篇文章 0 订阅
18 篇文章 0 订阅

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.

Show Tags

Have you met this question in a real interview?


思路: 首先, 凡是和括号有关的必须用 stack ,由于这个题要考虑断开的情况, 我们用一个 int 数组来存储 长度。

如果是左括号, 直接把index 存入stack, 如果是右括号, 而且stack 非空, 说明有可以匹配的左括号, 先获取做括号的位置, 然后这个有效长度为  i - pre  + 1  , 但如果前面也是有效的, 就可以连接上了,  因此 判断 pre > 0  , 来加上 valid[pre - 1]

易错点: 1. 忘记可以连接的情况,  2。 判断 pre > 0    3.括号长度是 i - pre  + 1  不是直接加2.

public class Solution {
    public int longestValidParentheses(String s) {
        int len = s.length();
        if(len < 1)
            return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int[] valid = new int[len];//Storage the valid parentheses length
        int max = 0;
        int cur = 0;
        for(int i = 0; i < len; i++){
            if(s.charAt(i) == '(')
                stack.push(i);
            else{
                if(!stack.isEmpty()){//-----
                    int pre = stack.pop();
                    valid[i] = i - pre + 1 + (pre > 0 ? valid[pre - 1] : 0);// 连接起来和前面的,防止()(()
                    max = Math.max(max, valid[i]);
                }
            }
        }
        return max;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值