我用栈写了方括号检查功能。似乎可以正常工作,但是当我输入'(((([[]] {}')作为参数(开始时很少重复的符号)时,它返回None。我认为它与stack len链接,但仍然没有弄清楚
<div class="header-css-class">
<ng-content select="div[role=header]"></ng-content>
</div>
<div class="body-css-class">
<ng-content select="div[role=body]"></ng-content>
</div>
经过一些重构,我做到了:
def func(brakets):
stack = []
for char in brakets:
if char in '([{':
stack.append(char)
# print(stack)
if len(stack) == 0:
return False
opener = stack.pop()
if opener == '(' and char != ')':
return False
if opener == '[' and char != ']':
return False
if opener == '{' and char != '}':
return False
if not stack:
return True
但还是同样的问题
def func(pattern):
stack = []
for bracket in pattern:
if bracket in dct.keys():
stack.append(bracket)
print(stack)
elif bracket in dct.values():
if len(stack) == 0:
return False
opened_bracket = stack.pop()
if dct[opened_bracket] != bracket:
return False
if not stack:
return True
,仍然没有。但是在循环结束且条件未完成的情况下,我放入了else语句
答案 0 :(得分:0)
您可能会遇到三种不匹配的情况:
在下面发布的代码中,该堆栈更像是一堆字典(在我的代码中称其为对类型),而不是将单个字符压入堆栈。给定的对类型告诉您,给定一个开始字符,弹出时您希望看到哪个结束字符。这样做的好处是简化了循环中的事情-检查最新的打开字符是否与当前的关闭字符匹配时,我们可以查找期望的关闭字符,而不是if语句链。这样做的另一个好处是,如果要添加新类型的对,可以在以后扩展is_balanced函数。
def is_balanced(string):
pair_types = [
{"open": "(", "close": ")"},
{"open": "[", "close": "]"},
{"open": "{", "close": "}"}]
def get_pair_type_from_open_char(open_char):
try:
return next(pair_type for pair_type in pair_types if pair_type["open"] == open_char)
except StopIteration:
# No such pair exists
return None
all_close_chars = "".join([pair_type["close"] for pair_type in pair_types])
stack = []
for char in string:
pair_type = get_pair_type_from_open_char(char)
if pair_type is not None:
stack.append(pair_type)
elif char in all_close_chars:
# We would like to pop
try:
top = stack.pop()
except IndexError:
# The stack was empty
return False
else:
# The stack was not empty
# However, the current open char (top of the stack)...
# ...needs to match the current close char
if top["close"] != char:
# The current pair of chars are mismatched (e.g. "(" and "]")
return False
# If there are things left over in the stack after the loop...
# ...this means we have open chars with no matching close chars
return not stack
def main():
string = "(())[({})]"
print("The string is" + [" not", ""][is_balanced(string)] + " balanced")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())