我有一个字符串,它看起来像这样{[]}{([])}()
,我循环查找它是一个开括号还是一个闭括号,并将它附加到列表中。
我现在想做的是找出哪一个是最深的鼻涕然后打印出来。所以在这个例子中,我会打印中间的{([
,但是我不知道怎么做。我可以附加开始的开放括号,然后重置它,但如何比较他们的夫妇,虽然,并打印最大的一个
我的代码:
def is_nested(str):
stack = []
deepest =[]
index=1
open=0
for c in str:
if c == "{" or c == "(" or c == "[" or c =="<":
stack.append(c) # this is push
deepest.append(c)
open +=1
index +=1
elif c == "}":
x = stack.pop()
index +=1
if x != "{":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received } instead." %(x2,index)
elif c == "]":
x = stack.pop()
index +=1
if x != "[":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received ] instead." %(x2,index)
elif c == ">":
x = stack.pop()
index +=1
if x != "<":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received > instead." %(x2,index)
elif c == ")":
x = stack.pop()
index +=1
if x != "(":
index -=1
x2=parens(x)
return "False: expected %s at character index %d, but received ) instead." %(x2,index)
check(str)
return True
def check(str):
deepest =[]
for c in str:
if c == "{" or c == "(" or c == "[" or c =="<":
deepest.append(c)
print deepest
def parens(x):
if x == "<":
return ">"
elif x =="(":
return ")"
elif x == "{":
return "}"
elif x == "[":
return "]"
print is_nested("{[()}")
print is_nested("([)")
print is_nested("{[]({})}")
print is_nested("<()>")
print is_nested("{(<)}")
我不确定我是否正确理解你的愿望,但这是最长的连续括号:
像这样的?你知道吗
此函数获取一个只包含大括号的字符串,并告诉您嵌套的最深级别,以及该级别嵌套的第一个实例的开始大括号的索引。另外,如果字符串未成形,它将引发错误。你知道吗
我已经将大括号以外的任何字符定义为错误,但这可以通过修改
else
条件来轻松更改。你知道吗您应该迭代并更新当前的开括号数,并保持循环时的最大值。如果长度大于max的curren length,则可以将所有开括号放在用作堆栈的字符串上,并使用此字符串更新max
相关问题 更多 >
编程相关推荐