题目
python实现代码
class Solution:
def isValid(self, s: str) -> bool:
par_dict = {'(': ')', '[': ']', '{': '}'}
index = 0
balanced = True
left_par = []
while index < len(s) and balanced:
symbol = s[index]
# 如果是左括号,则推入栈
if symbol in par_dict.keys():
left_par.append(symbol)
# 否则就是右括号,如果栈为空,说明不匹配,否则若删掉的符号与进入的符号在字典中是匹配的,则继续,否则就是不匹配
else:
if len(left_par) == 0:
balanced = False
else:
pop_par = left_par.pop()
if symbol != par_dict[pop_par]:
balanced = False
index += 1
if len(left_par) == 0 and balanced:
return True
else:
return False