Given a string s
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.
Example 1:
1 | Input: s = "()" |
Example 2:
1 | Input: s = "()[]{}" |
Example 3:
1 | Input: s = "(]" |
Example 4:
1 | Input: s = "([)]" |
Example 5:
1 | Input: s = "{[]}" |
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
stack
实际上就是用stack模拟括号. 思路简单, 但是细节多.
首先要判断是左括号还是右括号. 左括号直接push到栈里面, 右括号要先检查栈是不是空的, 是空的直接返回false. 不是空的检查栈顶元素和右括号是否匹配, 如果不匹配直接返回false. 匹配就pop.
遍历完string中每一个元素后, 要检查栈是否为空, 如果非空返回false, 空的返回true.
1 | class Solution { |