Given a string
s
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.
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Example 4:
Input: s = “([)]”
Output: false
Example 5:
Input: s = “{[]}”
Output: true
Constraints:
1 <= s.length <= 10<sup>4</sup>
s
consists of parentheses only '()[]{}'
.题目大意:
求给定字符串是否合法括号配对。
算法思路:
括号题优先考虑用Stack
注意事项:
- 三种不合法情况: ‘[‘ (stack有余), ‘]’ (要匹配的时候stack为空), ‘{]’ (不匹配)
Python代码:
1 | PARENTHESES_DICT = {'(': ')', '[': ']', '{': '}'} |
算法分析:
时间复杂度为O(n)
,空间复杂度O(n)