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.
样例:
1 | Input: "()" |
1 | Input: "()[]{}" |
1 | Input: "(]" |
题意:
给出一个字符串,判断其中括号是否匹配,’(‘ –> ‘)’,’[‘ –> ‘]’,’{‘ –> ‘}’
思路:
使用栈来进行判断:
如果是 ‘(‘、’[‘ 、’{‘ 这三个,则入栈
如果遇到 ‘)’、’]’、’}’ 这三个则判断栈顶是否为对应的匹配字符串,如果是则出栈,反之返回 false。
代码:
1 | class Solution { |
Runtime:4ms Memory:8.6MB