有效的括号

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();
    }

用栈实现队列

// 用栈实现队列,栈是FILO,队列是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) {
                // 扩容
                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;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容