text = 'aaaa(bb()()ccc)dd'
istart = [] # stack of indices of opening parentheses
d = {}
for i, c in enumerate(text):
if c == '(':
istart.append(i)
if c == ')':
try:
d[istart.pop()] = i
except IndexError:
print('Too many closing parentheses')
if istart: # check if stack is empty afterwards
print('Too many opening parentheses')
print(d)
检查平衡括号的标准方法是使用堆栈。在Python中,这可以通过附加到标准列表并从中弹出来完成:
结果:
你是说自动化的方法? 我不这么认为。
您需要使用堆栈创建一个程序,在其中找到左括号时推送索引,找到右括号时弹出索引。
在Python中,可以很容易地使用列表作为堆栈,因为它们有
append()
和pop()
方法。希望这有帮助。
相关问题 更多 >
编程相关推荐