# 判断一个字符串中的有效括号()[]{}是否有效 def is_invalid(s): stack = [] for i in s: # 遇到左括号,则添加到堆栈中 if i == '(' or i == '[' or i == '{': stack.append(i) else: # 遇到右括号, 先判断堆栈中是否有值, 如果没有,说明多了一个右括号, 直接返回False if len(stack) == 0: return False # 判断右括号与堆栈中的栈顶元素是否匹配,匹配则pop,否则返回False if (i == ')' and stack[-1] == '(' ) or (i == ']' and stack[-1] == '[') or (i == '}' and stack[-1] == '{'): stack.pop() else: return False return len(stack) == 0 if __name__ == '__main__': print(is_invalid('1{}()[]')) print(is_invalid('{}()[]'))