描述
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
示例1
输入:
"["
返回值:
false
示例2
输入:
"[]"
返回值:
true
栈操作
#
#
# @param s string字符串
# @return bool布尔型
#
stack = []
def match(c1 , c2)->bool:
if c1 == '(' and c2 == ')':
return True
if c1 == '[' and c2 == ']':
return True
if c1 == '{' and c2 == '}':
return True
return False
def in_stack(c):
stack.append(c)
def out_stack(c):
m = stack[-1]
if match(m, c):
stack.pop(-1)
return True
else:
return False
def left(c)->bool:
if c == '[' or c == '(' or c == '{':
return True
return False
class Solution:
def isValid(self , s ):
for c in s:
if left(c):
in_stack(c)
else:
if len(stack) == 0:
return False
if not out_stack(c):
return False
if len(stack) > 0:
return False
return True
# write code here