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: Input: "{[]}" Output: true
思路
我们可以设置一个辅助空间栈来保存括弧的左半边,然后进行遍历。当遍历到不是右半边括弧时,我们就弹出最上面的括弧来和当前括弧进行对比,查看是否是有效括弧。 时间复杂度为O(n)(n为字符串的长度), 空间复杂度为O(n)。
图示思路
一直到遍历完毕
代码
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) < : # 空字符串直接返回
return True
tem_dict = {')':'(', '}':'{', ']':'['} # 设置辅助字典
stack = [] # 设置辅助栈
for i in s: # 进行遍历
if i not in tem_dict:
stack.append(i)
else:
if stack: # 右括弧进行选择
t = stack.pop()
if t != tem_dict[i]:
return False
else:
return False
if stack: # 栈不为空的话返回False
return False
return True