有效的括號(hào)

public boolean isValid(String s) {
        if (s == null) {
            return false;
        }
        Map<Character, Character> map = new HashMap<>();
        map.put(')','(');
        map.put('}','{');
        map.put(']','[');

        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '{' ||c == '[' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char p = stack.pop();
                if (map.get(c) != p) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

用棧實(shí)現(xiàn)隊(duì)列

// 用棧實(shí)現(xiàn)隊(duì)列,棧是FILO,隊(duì)列是FIFO
    static class MyQueue {
        int[] arr;
        int defaultLength = 10;
        int currentLength = 0;
        int length;

        /** Initialize your data structure here. */
        public MyQueue() {
            arr = new int[defaultLength];
            length = defaultLength;
        }

        /** Push element x to the back of queue. */
        public void push(int x) {
            if (currentLength == length) {
                // 擴(kuò)容
                int[] newArr = new int[arr.length * 2];
                for (int i = 0; i < arr.length; i ++) {
                    newArr[i] = arr[i];
                }
                arr = newArr;
            }
            arr[currentLength++] = x;
        }

        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            int value = arr[0];
            currentLength --;
            for (int i = 0; i < currentLength ; i ++) {
                arr[i] = arr[i + 1];
            }
            return value;
        }

        /** Get the front element. */
        public int peek() {
            return arr[0];
        }

        /** Returns whether the queue is empty. */
        public boolean empty() {
            return currentLength == 0;
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容