[LeetCode] 20. Valid Parentheses ☆(括号匹配问题)

转载:https://leetcode.windliang.cc/leetCode-20-Valid%20Parentheses.html

描述

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

解析

括号匹配问题。

如果只有一种括号,我们完全可以用一个计数器 count ,遍历整个字符串,遇到左括号加 1 ,遇到右括号减 1,遍历结束后,如果 count 等于 0 ,则表示全部匹配。但如果有多种括号,像 ( [ ) ] 这种情况它依旧会得到 0,所以我们需要用其他的方法。类似大学里面写的计算器。

栈!

遍历整个字符串,遇到左括号就入栈,然后遇到和栈顶对应的右括号就出栈,遍历结束后,如果栈为空,就表示全部匹配。

代码

public boolean isValid(String s) {
        Stack<Character> brackets = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
            case '(':
            case '[':
            case '{':
                brackets.push(c);
                break;
            case ')':
                if (!brackets.empty()) {
                    if (brackets.peek() == '(') {
                        brackets.pop();
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
                break;
            case ']':
                if (!brackets.empty()) {
                    if (brackets.peek() == '[') {
                        brackets.pop();
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
                break;
            case '}':
                if (!brackets.empty()) {
                    if (brackets.peek() == '{') {
                        brackets.pop();
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }

            }
        }

        return brackets.empty();
    }
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10522081.html