leetcode32——最长有效括号

题意:只包含 '('   ')'  寻找最长有效的括号,格式正确且连续如:

符合题意的

(()——2        )()())——4        ()(()——2        ()()()(()——6        ()(())——6

我一开始想用hashmap  加栈做 但是不全

class Solution {
    public int longestValidParentheses(String s) {
        //能够连续匹配  ()((()))  也符合
        if(s==null||s.length()==1) return 0;
        Map<Character,Character> hash=new HashMap<>();
        hash.put(')','(');
        Stack stack=new Stack();

        int count=0;
        int len=s.length();
        int max_len=0;
        for(int i=0;i<len;i++){
            if(hash.containsKey(s.charAt(i))){//包含右括号

                //栈不为空 且 有左括号和右括号匹配
                if(!stack.empty() && stack.peek()==hash.get(s.charAt(i)) ){
                    count+=2;
                    stack.pop();
                }else{
                    max_len=Math.max(max_len,count);//r如果右括号 匹配终端
                    count=0;
                }
            }else{//左括号
                //栈为空时入栈 否则不入栈
                /*if(stack.empty()){
                    stack.push(s.charAt(i));
                }else{
                    //max_len=Math.max(max_len,count);//6
                    //count=0;
                    continue;
                }*/

                stack.push(s.charAt(i));
            }

        }

        return max_len>count?max_len:count;
    }
}

 官方给的解答:

class Solution {
    public int longestValidParentheses(String s) {
        int maxans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    maxans = Math.max(maxans, i - stack.peek());
                }
            }
        }
        return maxans;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

官方的规律是  连续且有效,即找到未匹配的右括号的额位置  与最远且匹配了的位置的距离即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值