LeetCode-20. 有效的括号

题目链接

https://leetcode.cn/problems/valid-parentheses/

题目描述

在这里插入图片描述

题解

题解1

首先这个字符串里只会包含括号,不会有其他的东西
其次,匹配的括号一定成对,但是不一定都是首尾呼应的,比如()[]{}如果我们使用双指针前后遍历是通不过的
所以,使用栈最合适,某个左括号压入栈后,最近的应该与其匹配的括号一定是在栈顶的
比如:({})
碰到:(,压入
碰到:[,压入
碰到:],弹出[,匹配
碰到:(,压入
碰到:),弹出(,匹配
碰到:{,压入
碰到:},弹出{,匹配
碰到:),弹出(,匹配

    public boolean isValid(String s) {

        // 定义一个栈
        LinkedList<Character> stack = new LinkedList<>();

        // 遍历字符串
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '(') {
                stack.push(')');
            } else if (c == '[') {
                stack.push(']');
            } else if (c == '{') {
                stack.push('}');
            } else {
                if (stack.isEmpty() || stack.pop() != c)
                    return false;
            }
        }

        return stack.isEmpty();

    }

题解2

当然,如果题解1看着难看,也可以看看题解2,思路基本上是一样的

    public boolean isValid(String s) {

        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');

        LinkedList<Character> stack = new LinkedList<>();

        // 遍历字符串
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            // 如果都是右括号,弹出栈元素进行比较
            if (c == ')' || c == ']' || c == '}') {
                if (stack.isEmpty() || stack.pop() != map.get(c))
                    return false;
            } else {
                // 如果都是左括号,把元素压入栈
                stack.push(c);
            }
        }

        return stack.isEmpty();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值