20. 有效的括号
给定一个只包括 '(',')','{','}','[',']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 空字符串可被认为是有效字符串。
示例:
输入1:
"()"
输出1:
True
输入2:
"()[]{}"
输出2:
True
输入3:
"([)]"
输出3:
False
解答:
def isValid(self, s):
if s is None or len(s) == 0 : return True
stack = []
for char in s:
if char in ['(','[','{']:
stack.append(char)
else :
if char == ')':
if stack == [] or stack[-1] != '(':
return False
else:
stack.pop()
elif char == ']':
if stack == [] or stack[-1] != '[':
return False
else:
stack.pop()
else:
if stack == [] or stack[-1] != '{':
return False
else:
stack.pop()
return True if len(stack) == 0 else False