20. 【简单】有效的括号


链接

题目描述

在这里插入图片描述

利用栈

1.思路

如果是左括号,就入栈;如果是右括号,栈不空并且栈顶是对应的左括号,那就出栈,否则返回 false

代码

class Solution {
    public boolean isValid(String s) {
        if(s == null || s.length() == 0){
            return true;
        }
        Stack<Character> stack = new Stack<>();
        
        for(int i = 0; i < s.length() ;i++){
            if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
                stack.push(s.charAt(i));
                continue;
            }
            if(s.charAt(i) == ')'){
                if(!stack.isEmpty() && stack.peek() == '('){
                    stack.pop();
                    continue;
                }else{
                    return false;
                }
            }
            if(s.charAt(i) == ']'){
                if(!stack.isEmpty() && stack.peek() == '['){
                    stack.pop();
                    continue;
                }else{
                    return false;
                }
            }
            if(s.charAt(i) == '}'){
                if(!stack.isEmpty() && stack.peek() == '{'){
                    stack.pop();
                    continue;
                }else{
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

2.栈+map:写法更简便

class Solution {
    public boolean isValid(String s) {
        if(s == null || s.length() == 0){
            return true;
        }
        Map<Character,Character> map = new HashMap<>();
        map.put(')','(');
        map.put(']','[');
        map.put('}','{');
        Stack<Character> stack = new Stack<>();
        
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(map.containsKey(ch)){
                char top = stack.isEmpty() ? '#' : stack.pop();
                if(top != map.get(ch)){
                    return false;
                }
            }else{
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}
发布了55 篇原创文章 · 获赞 1 · 访问量 881

猜你喜欢

转载自blog.csdn.net/weixin_42469108/article/details/103638352
今日推荐