20. 有效的括号 + 栈 + 括号匹配

20. 有效的括号

LeetCode_20

题目描述

相似题目

题号 题目 备注
20 有效的括号
22 括号生成 dfs
5 最长回文子串 dp
647 回文子串 dp
32 最长有效括号 dp
678 有效的括号字符串 栈、dp

方法一:使用常规思路-使用栈匹配括号

class Solution {
    public boolean isValid(String s) {
        int len = s.length();
        if((len & 1) == 1)
            return false;
        Stack<Character> sta = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');
        for(int i=0; i<len; i++){
            char ch = s.charAt(i);
            if(sta.isEmpty())
                sta.push(ch);
            else{
                if(ch == map.getOrDefault(sta.peek(), '#')){//注意这里不能直接使用map.get方法,因为我们的map只存储了三种情况,实际上可能会出现6种字符
                    sta.pop();
                }else sta.push(ch);
            }
        }
        return sta.isEmpty();
    }
}

方法二:更高效解法

  1. 本题可以扩展一下思维,map中存储反括号和正括号对,因为一旦出现了反括号,栈顶的元素一定要是正括号,否则匹配必定失败。
  2. 要注意初始栈为空的情况。
class Solution {
    public boolean isValid(String s) {
        int len = s.length();
        if((len & 1) == 1)
            return false;
        Stack<Character> sta = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put('}', '{');
        map.put(']', '[');
        for(int i=0; i<len; i++){
            char ch = s.charAt(i);
            if(map.containsKey(ch)){
                if(sta.isEmpty() || sta.peek() != map.get(ch))
                    return false;
                sta.pop();
            }else{
                sta.push(ch);
            }
        }
        return sta.isEmpty();
    }
}
posted @ 2021-03-13 11:59  Garrett_Wale  阅读(75)  评论(0编辑  收藏  举报