作者: 奋斗的韭菜汪 | 来源:发表于2022-04-07 14:26 被阅读0次

    有效括号

    Click here for leetcode details

    class Solution {
        public boolean isValid(String s) {
            if (s == null || s.length() == 0){
                return false;
            }
            Stack<Character> stack = new Stack<>();
            for(char c : s.toCharArray()){
                if (c == '(' || c == '[' || c == '{'){
                    stack.push(c);
                //这里容易漏掉,需注意
                } else if(stack.empty() && (c == ')' || c == ']'||c == '}')){
                    return false;
                }else{
                    char a = stack.pop();
                    if (a == '(' && c != ')'){
                        return false;
                    }
                    if (a == '[' && c != ']'){
                        return false;
                    }
                    if (a == '{' && c != '}'){
                        return false;
                    } 
                }
            }
            return stack.empty();
        }
    }
    

    最小栈

    Click here for leetcode details

    class MinStack {
        Stack<Integer> stack;
        Stack<Integer> minStack;
    
        public MinStack() {
            stack = new Stack();
            minStack = new Stack();
    
        }
        
        public void push(int val) {
            stack.push(val);
            if(minStack.empty() || minStack.peek() > val){
                minStack.push(val);
            } else {
                //注意这里,如果不push自身的话,pop会空栈异常
                minStack.push(minStack.peek());
            }
        }
        
        public void pop() {
            stack.pop();
            minStack.pop();
        }
        
        public int top() {
            return stack.peek();
        }
        
        public int getMin() {
            return minStack.peek();
        }
    }
    

    相关文章

      网友评论

          本文标题:

          本文链接:https://www.haomeiwen.com/subject/bttssrtx.html