|
发表于 2021-6-23 11:32:03
|
显示全部楼层
瞎搞版:
def KuoHao(a, b, c, d):
if c < d:
if temp.find(a, c, d) == -1:
if temp.find(b, c, d) != -1:
return 1
elif temp.find(b, c, d) == -1:
return 1
elif (temp.find(a, c, d) - temp.find(b, c, d)) % 2 == 0:
return 1
return KuoHao(a, b, temp.find(a, c, d) + 1, temp.find(b, c, d))
else:
return 0
temp = input('请输入测试字符串:')
li = list('()[]{}')
K = []
for i in range(0, 6, 2):
K.append(KuoHao(li[i], li[i + 1], 0, len(temp)))
print('非法') if 1 in K else print('合法')
看了思路:
Str = input('请输入测试字符串:')
dictKH = {')': '(', ']': '[', '}': '{'}
LKH = ['(', '[', '{']
RKH = [')', ']', '}']
S = []
for i in Str:
if i in LKH:
S.append(i)
elif i in RKH:
if len(S) == 0 or S.pop() != dictKH[i]:
print('非法')
break
else:
print('合法')
|
|