我需要使用堆栈检查字符串是否具有平衡的括号,但我的测试用例之一是错误的,因为括号甚至不相等,但返回的是True。
class Stack:
def __init__(self):
self.list = []
def is_empty(self):
if len(self.list) == 0:
return True
else:
return False
def push(self, item):
self.list.append(item)
def pop(self):
return self.list.pop()
def peek(self):
return self.list[-1]
def balanced_brackets(text):
s = Stack()
opening = '(<'
closing = ')>'
mapping = dict(zip(opening, closing))
for letter in text:
if letter in opening:
s.push(mapping[letter])
elif letter in closing:
if not s or letter != s.pop():
return False
return True
'''
print(balanced_brackets('(<x>)(())()'))#this test case is correct
print(balanced_brackets('(((((((xyz))))))'))#but this is wrong
'''
答案 0 :(得分:0)
您可以使用collections.Counter
对象只计算出括号的数量,然后比较这些数字以确定余额:
from collections import Counter
cnt = Counter('(((((((xyz))))))')
if cnt['('] != cnt[')']:
print('unbalanced')
我认为您知道了并且可以在此基础上进行构想。
答案 1 :(得分:0)
您必须在for
循环结束时检查堆栈:
def balanced_brackets(text):
s = Stack()
opening = '(<'
closing = ')>'
mapping = dict(zip(opening, closing))
for letter in text:
if letter in opening:
s.push(mapping[letter])
elif letter in closing:
if s.is_empty() or letter != s.pop():
return False
if not s.is_empty():
return False
return True
输出:
print(balanced_brackets('(<x>)(())()'))
print(balanced_brackets('(((((((xyz))))))'))
True
False