Catalogue
Question
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:
Analysis
相比于采用多个 if else
来判断括号,使用字典储存括号对应关系并用于判断更加简洁。如果当前字符为 '{(['
之一,则往一个额外列表中添加左括号,否则如果额外列表为空,或者当前括号和额外列表最后一个括号不对应,则不符合规则。
Code
1 | class Solution(object): |