【发布时间】:2019-11-26 23:05:05
【问题描述】:
给定一个只有“}”和“{”的表达式。表达可能不平衡。找到使表达式平衡的最小括号反转次数
…。 Python `` a=['}{}{}{}}}{{{{{}{}{}}{{}{}{}}{{}}{{']
for elem in a:
sol=0
stack=[]
#stack.append(elem[i])
i=0
while i<len(elem)-1:
if elem[i]=='{' and elem[i+1]=='{':
stack.append(elem[i])
stack.append(elem[i+1])
sol+=1
elif elem[i]=='}' and elem[i+1]=='{':
if len(stack)!=0:
if stack[-1]=='{':
stack.pop()
stack.append(elem[i+1])
else:
stack.append(elem[i])
stack.append(elem[i+1])
sol+=1
else:
stack.append(elem[i])
`` stack.append(elem[i+1])
sol+=2
elif elem[i]=='}' and elem[i+1]=='}':
if len(stack)!=0:
if stack[-1]=='{' and stack[-2]=='{':
stack.pop()
stack.pop()
sol-=1
elif stack[-1]=='{' and stack[-2]=='}':
stack.pop()
stack.append(elem[i+1])
else:
stack.append(elem[i])
stack.append(elem[i+1])
sol+=1
else:
stack.append(elem[i])
stack.append(elem[i+1])
sol+=1
i+=2
print(sol)
….
预计 5 输出 6
【问题讨论】:
-
如果您需要方法,请查看我的回答和回复。
-
非常感谢阿达什