LeetCode 20. 有效的括号

20. 有效的括号

Solution

思路:左边入栈,遇到右边判断即可,最后看堆栈是否为空。

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        char[] str = s.toCharArray();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
                stack.push(str[i]);
            } else {
                if (stack.empty()) return false;
                char ch = stack.peek();
                if (str[i] == ')') {
                    if (ch != '(') return false;
                } else if (str[i] == ']') {
                    if (ch != '[') return false;
                } else {
                    if (ch != '{') return false;
                }
                stack.pop();
            }
        }
        if (stack.empty()) return true;
        else return false;
    }
}

不过Stack类不推荐使用,可以使用Deque

实现类ArrayDequeLinkedList的区别:

ArrayDeque数组实现,随机存取效率高,队列、栈的效率好一点,循环数组的删除不涉及元素的移动

LinkedList插入、删除的优势更大

class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');
        Deque<Character> deque = new ArrayDeque<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                if (deque.size() == 0 || deque.peek() != map.get(c)) {
                    return false;
                }
                deque.pop();
            } else {
                deque.push(c);
            }
        }
        if (deque.size() == 0) {
            return true;
        } else {
            return false;
        }
    }
}
posted @ 2022-03-16 21:46  Frontierone  阅读(26)  评论(0编辑  收藏  举报