Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Concise algorithm solution in Speedy category for Remove Brackets by Igor_Sekretarev
from functools import lru_cache
OPPOSITE = {
'{' : '}',
'(' : ')',
'[' : ']'
}
def is_correct(brackets: str) -> bool:
stack = []
for bracket in brackets:
if bracket in '{([':
stack.append(bracket)
continue
if not stack or OPPOSITE[stack.pop()] != bracket:
return False
return not stack
@lru_cache
def remove_brackets(line: str) -> str:
if is_correct(line):
return line
return max((remove_brackets(line[:i] + line[i+1:])
for i in range(len(line))), key=len)
if __name__ == '__main__':
print("Example:")
print(remove_brackets('(()()'))
# These "asserts" are used for self-checking and not for an auto-testing
assert remove_brackets('(()()') == '()()'
assert remove_brackets('[][[[') == '[]'
assert remove_brackets('[[(}]]') == '[[]]'
assert remove_brackets('[[{}()]]') == '[[{}()]]'
assert remove_brackets('[[[[[[') == ''
assert remove_brackets('[[[[}') == ''
assert remove_brackets('') == ''
assert remove_brackets('[(])') == '()'
print("Coding complete? Click 'Check' to earn cool rewards!")
April 28, 2021
Comments: