美国求职-刷题Day3

20. Valid Parentheses

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, '['and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.

最开始的思路是做个通过map来分别储存左右括号,同时使用计数器来统计各个括号的数量,可以解决"({[]})"的情况,但无法针对各个括号的位置,类似“([)]”的情况。进一步思考,我们想到了栈的算法,先进后出

 public boolean isValidByStack(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();

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

        for (int i = 0; i < chars.length; i++) {
            if (map.containsKey(chars[i])) {
                char topElement = stack.isEmpty() ? '#' : stack.pop();
                if (topElement != map.get(chars[i])) {
                    return false;
                }
            } else {
                stack.push(chars[i]);
            }
        }

        return stack.empty();
    }

如果进入的是反括号,则把栈顶的pop出来进行比较,如果不是一对则返回false,如果一致则该对括号都被pop,直到最后整个栈空了,返回true
这里发现题解里有个奇淫技巧的方法,一起来分享下:

    public boolean isValid(String s) {
        while (s.contains("{}") || s.contains("[]") || s.contains("()")) {
            s = s.replace("{}", "");
            s = s.replace("[]", "");
            s = s.replace("()", "");
        }
        return "".equals(s);
    }

不断的逐对替换括号,最后来判断结果是否为空,虽然效率不高,但是思路不得不让人拍案叫绝!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值