20 有效的括号(LeetCode HOT 100)

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

示例 1:

输入:s = "()"
输出:true

示例 2:

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

示例 3:

输入:s = "(]"
输出:false

示例 4:

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

示例 5:

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

示例 6:

输入:s = "}"
输出:false

提示:
1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成

Soulution:

public class L20IsValid {
    public static void main(String[] args) {
        String s = "()";
        // true
        System.out.println(isValid(s));
        s = "()[]{}";
        // true
        System.out.println(isValid(s));
        s = "(]";
        // false
        System.out.println(isValid(s));
        s = "([)]";
        // false
        System.out.println(isValid(s));
        s = "{[]}";
        // true
        System.out.println(isValid(s));
        s = "}";
        // true
        System.out.println(isValid(s));
    }


    /**
     * 存储括号对应关系
     */
    static HashMap<Character, Character> bracketMap = new HashMap<Character, Character>() {{
        put(')', '(');
        put(']', '[');
        put('}', '{');
    }};

    public static boolean isValid(String s) {
        Stack<Character> waitMatchStack = new Stack<>();
        char[] chars = s.toCharArray();
        for (char aChar : chars) {
            if (bracketMap.containsKey(aChar)) {
                if (waitMatchStack.isEmpty()) {
                    return false;
                } else if (!bracketMap.get(aChar).equals(waitMatchStack.pop())) {
                    return false;
                }
            } else {
                waitMatchStack.push(aChar);
            }
        }
        return waitMatchStack.isEmpty();
    }
}

Idea:
括号匹配,自然而然想到用栈解决。
不过要注意栈空的情况。

Reslut:

posted @ 2022-04-10 13:52  supermingjun  阅读(33)  评论(0编辑  收藏  举报