|
发表于 2022-5-4 20:09:34
|
显示全部楼层
# 题干:
# 字符串仅包含 '()'、'[]'、'{}' 这三对括号的组合
# 左右括号必须成对编写,比如 "()" 是合法的,"(" 则是非法的
# 左右括号必须以正确的顺序闭合,比如 "{()}" 是合法的,"{(})" 则是非法的
char = '''()[]{}'''
strings = input('请输入测试字符串:')
stack1 = []
stack2 = []
for each in strings:
if each not in char:
print('非法-_-')
break
if (each=='(') or (each=='[') or (each=='{'):
stack1.append(each)
else:
if len(stack1) == 0:
print('非法-_-')
break
if each == ')':
each = '('
if each == ']':
each = '['
if each == '}':
each = '{'
stack2.insert(0, each)
if stack1.pop() == stack2[0]:
stack2.remove(stack2[0])
else:
if stack1 == stack2:
print('合法o_o')
else:
print('非法-_-') |
|