20. Valid Parentheses

yPhantom 2019年10月14日 33次浏览

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

Solution

这个题主要注意char的装箱类型是Character.

Java版本:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> m = new HashMap<>();
        m.put('(', ')');
        m.put('[', ']');
        m.put('{', '}');
        for (char c: s.toCharArray()) {
            if (m.containsKey(c)) {
                stack.push(m.get(c));
            } else if (stack.isEmpty() || stack.pop() != c) {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

python版本:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        m = {"(": ")", "[": "]", "{": "}"}
        for c in s:
            if c in m.keys():
                stack.append(m.get(c))
            elif len(stack) == 0 or stack.pop() != c:
                return False
        return len(stack) == 0