leetcode做题总结,题目Longest Valid Parentheses 2012/02/29

本文介绍了一种使用栈来解决最长有效括号匹配问题的算法。通过遍历字符串并将左括号的位置压入栈中,遇到右括号时检查是否能与栈顶元素匹配并更新最大有效括号长度。

找出最长匹配括号,我的方法是用栈储存,把"("入栈,遇到")"和栈顶匹配,匹配成功则出栈如果无法匹配就入栈。这样全部运行一遍后栈里就剩下没匹配的了,而这些元素之间就是各个能匹配的括号的队列。我的方法是用一个新的栈储存栈里每个元素的位置信息,这样用最后剩余的元素的位置信息相减就是各个括号队列的长度。


注意:这道题在OJ系统上遇到了点问题,一个是代码中的curr=m1-0;我之前写的是curr=m1-0+1;系统未报错,这里不能用0,因为0也是位置量,所以应该是-1。第二个问题是,注释掉本没用的s1.push(a.length);同样的代码在本地输入"()"输出2而在线输出0,我查了下,在线S1栈里会多出来一个0,不知道为什么。 所以OJ上AC了也不能保证代码的绝对正确啊。


public int longestValidParentheses(String s) {
        if(s.equals(""))return 0;
        int max=0;
        int curr=0;
        String[] a = s.split("");
        Stack<Integer> s1= new Stack<Integer>();
        Stack<String> s2= new Stack<String>();
        for(int r=0;r<a.length;r++){
            if(a[r].equals("(")){
                s1.push(r);
                s2.push(a[r]);
            }else{
                if(s1.isEmpty()){
                    s1.push(r);
                    s2.push(a[r]);
                }else{
                    if(s2.peek().equals("(")){
                        s1.pop();
                        s2.pop();
                    }else{
                        s1.push(r);
                        s2.push(a[r]);
                    }
                }
            }
        }
        s1.push(a.length);       //见我的注释
        
        if(s1.isEmpty()){
            max= s.length();
        }else{
            int m1=s1.pop();
            int m2;
            while(!s1.isEmpty()){
                m2=s1.pop();
                curr=m1-m2-1;
                if(curr>max)max=curr;
                m1=m2;
            }
            curr=m1-0;    //
            if(curr>max)max=curr;
        }
        return max;
        
    }


Update 2015/08/21: 上面的方法很复杂,下面是一个简单地算法,这个题是求最长子串,不是简单的求配对数量。

public class Solution {
    public int longestValidParentheses(String s) {
        int res = 0;
        Stack<Integer> stack = new Stack<Integer>();
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == ')' && !stack.isEmpty() && arr[stack.peek()] == '(') {
                stack.pop();
                if (stack.isEmpty()) res = i + 1;
                else res = Math.max(res, i - stack.peek());
            } else stack.push(i);
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值