0609-2020-LEETCODE-有效的括号对(栈的典型应用)

自己写的是纯用栈写的,只判断是不是右括号,可以直接抵消的话继续进行,否则就匹配不上,左括号直接进,最后返回栈是否为空。

	public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (stack.isEmpty()) stack.addLast(c);
            else {
                if (c == ')') {
                    if (stack.peekLast() == '(') stack.pollLast();
                    else return false;
                } else if (c == '}') {
                    if (stack.peekLast() == '{') stack.pollLast();
                    else return false;
                } else if (c == ']') {
                    if (stack.peekLast() == '[') stack.pollLast();
                    else return false;
                } else {
                    stack.addLast(c);
                }
            }
        }
        return stack.isEmpty();
    }

代码优化的话可以用map实现不用那么多判断

	private static final Map<Character,Character> map = new HashMap<Character,Character>(){{
        put('{','}'); put('[',']'); put('(',')'); put('?','?');
    }};
    public boolean isValid(String s) {
        if(s.length() > 0 && !map.containsKey(s.charAt(0))) return false;
        LinkedList<Character> stack = new LinkedList<Character>() {{ add('?'); }};
        for(Character c : s.toCharArray()){
            if(map.containsKey(c)) stack.addLast(c);
            else if(map.get(stack.removeLast()) != c) return false;
        }
        return stack.size() == 1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值