Longest Valid Parentheses leetcode java

本文介绍了一种利用栈解决最长有效括号子串问题的方法,通过遍历字符串并记录最长合法序列来找到最大长度。

题目:

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.

 

题解:

这道题是求最长匹配括号的长度,而不是个数,我最开始想错了,去写个数去了。。。

题解引用自:http://codeganker.blogspot.com/2014/03/longest-valid-parentheses-leetcode.html

这道题是求最长的括号序列,比较容易想到用栈这个数据结构。基本思路就是维护一个栈,遇到左括号就进栈,遇到右括号则出栈,并且判断当前合法序列是否为最 长序列。不过这道题看似思路简单,但是有许多比较刁钻的测试集。具体来说,主要问题就是遇到右括号时如何判断当前的合法序列的长度。比较健壮的方式如下:
(1) 如果当前栈为空,则说明加上当前右括号没有合法序列(有也是之前判断过的);
(2) 否则弹出栈顶元素,如果弹出后栈为空,则说明当前括号匹配,我们会维护一个合法开始的起点start,合法序列的长度即为当前元素的位置 -start+1;否则如果栈内仍有元素,则当前合法序列的长度为当前栈顶元素的位置下一位到当前元素的距离,因为栈顶元素后面的括号对肯定是合法的,而 且左括号出过栈了。
因为只需要一遍扫描,算法的时间复杂度是O(n),空间复杂度是栈的空间,最坏情况是都是左括号,所以是O(n)。

 

 

然后网上找了解法,有些人使用了DP,我没仔细看。。主要还是吸取了栈的思想。代码引用自:http://rleetcode.blogspot.com/2014/01/longest-valid-parentheses.html, 个人稍作修改。

如下所示:

public static int longestValidParentheses(String s) {
        if (s==null||s.length()==0){
            return 0;
            }
        
        int start=0;
        int maxLen=0;
        Stack<Integer> stack=new Stack<Integer>();
        
        for (int i=0; i<s.length();i++){
            if (s.charAt(i)=='('){
                stack.push(i);
            }else{
                if (stack.isEmpty()){
                    // record the position before first left parenthesis
                    start=i+1;
                }else{
                    stack.pop();
                    // if stack is empty mean the positon before the valid left parenthesis is "last"
                    if (stack.isEmpty()){
                        maxLen=Math.max(i-start+1, maxLen);
                    }
                    else{
                        // if stack is not empty, then for current i the longest valid parenthesis length is
                        // i-stack.peek()
                        maxLen=Math.max(i-stack.peek(),maxLen);
                    }
                }
            }
        }
            return maxLen;
            }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值