LeetCode棧相關高頻題(七)

大家好,我是方圓
無它,唯手熟爾

20.

在這裏插入圖片描述
在這裏插入圖片描述

class Solution {
    public boolean isValid(String s) {
        //奇數長度返回false
        if(s.length() % 2 == 1){
            return false;
        }

        //創建棧,開始暴力循環
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i < s.length();i++){
            char theChar = s.charAt(i);

            if(theChar == '(' || theChar == '[' || theChar == '{' ){
                stack.push(theChar);
                continue;
            }else{
                //在棧空且字符不是括號的左邊
                if(stack.empty()){
                    return false;
                }

                //棧非空,判斷它是否匹配
                //peek()方法拿出棧頂的元素,但是不彈棧
                char pre = stack.peek();
                if((pre == '(' && theChar == ')') ||
                   (pre == '[' && theChar == ']') ||
                   (pre == '{' && theChar == '}')){
                       //符合條件,彈出括號的左邊兒
                       stack.pop();
                   }else{
                       return false;
                   }
            }
        }

        return stack.empty();
    }
}

155. 最小棧

在這裏插入圖片描述

class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    /** initialize your data structure here. */
    public MinStack() {
        stack = new Stack();
        minStack = new Stack();
    }
    
    public void push(int x) {
        stack.push(x);
        if(minStack.empty() || x <= minStack.peek()){
            minStack.push(x);
        }
    }
    
    public void pop() {
        //這裏的stack.pop()也會彈棧,所以不需要另外寫出stack的彈棧
        if(stack.pop().equals(minStack.peek())){
            minStack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

邊看邊練纔行啊!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章