首页 > 其他分享 >Leetcode.20 有效括号

Leetcode.20 有效括号

时间:2024-07-15 21:08:00浏览次数:12  
标签:false 有效 else queue 括号 字符串 push 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();
    }

 

标签:false,有效,else,queue,括号,字符串,push,Leetcode.20
From: https://www.cnblogs.com/wdh01/p/17473630.html

相关文章