0
点赞
收藏
分享

微信扫一扫

【2022初春】【LeetCode】20. 有效的括号

飞鸟不急 2022-01-28 阅读 54

思路正确,注意map的多个初始化

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        Map<Character,Character> map = new HashMap<>(){{
            put('{','}');
            put('(',')');
            put('[',']');
            }};
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
                stack.push(s.charAt(i));
            }else {
                if(stack.isEmpty()||s.charAt(i)!=map.get(stack.peek())) return false;
                else stack.pop();
            }
        }
        if(stack.isEmpty()) return true;
        else return false;
    }
}
举报

相关推荐

0 条评论