Leetcode.20 有效括号

题目描述

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。

示例

输入:s = "()"
输出:true
输入:s = "()[]{}"
输出:true
输入:s = "(]"
输出:false

参考实现c

    public static boolean isValid(String s) {
        Deque<Character> queue = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                queue.push(')');
            } else if (c == '[') {
                queue.push(']');
            } else if (c == '{') {
                queue.push('}');
            } else if (queue.isEmpty() || queue.peek() != c) {
                return false;
            } else {
                queue.pop();
            }
        }
        return queue.isEmpty();
    }

 

posted @ 2024-07-15 21:04  晓枫的春天  阅读(3)  评论(0编辑  收藏  举报