I don't have a formal description for this problem, but here are the parameters:
- Given a string
S
check that each opening bracket has a matching closing bracket. - Any nesting violations are invalid.
- Assume multiple nested sets of similar brackets are invalid.
Because the nesting level matters and we can't just arbitrarily count brackets, my solution is to generate an array of substrings that contain each bracket level and check for violations.
Is there a way to make this more efficient?
bracket_levels.py
import re
def hasClosedBrackets(s: str) -> bool:
brackets = dict([('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')])
for (opener, closer) in brackets.items():
pattern = r'(?<=\{}).+?(?=\{})'.format(opener, closer)
for match in re.findall(pattern, s):
for (o,c) in brackets.items():
if match.count(o) != match.count(c):
return False
return True
# The first four test cases are true, the last four are false
for test in ['(){}[]', '()[{}]', '<as>df', '(<[{a}s]>d)f', '()[{]}', '<as(>df)', '{as<df}', '(())',]:
print(test, ':', hasClosedBrackets(test))
Output
(){}[] : True
()[{}] : True
<as>df : True
(<[{a}s]>d)f : True
()[{]} : False
<as(>df) : False
{as<df} : False
(()) : False