Skip to content

Instantly share code, notes, and snippets.

@anviar
Last active September 24, 2019 13:28
Show Gist options
  • Save anviar/0c6019dc91282e726fcd7c6936e56078 to your computer and use it in GitHub Desktop.
Save anviar/0c6019dc91282e726fcd7c6936e56078 to your computer and use it in GitHub Desktop.
import logging
logging.basicConfig(
format='[%(levelname)s] %(message)s',
level=logging.DEBUG,
)
# some_str = '()]]((}{))()[()]'
some_str = '(((((()()((}{))()[()]'
pairs = {
'{': '}',
'[': ']',
'(': ')',
}
def test_str(in_str: str) -> str:
openned = list()
results = list()
match = str()
for c in in_str:
if c in pairs.keys():
openned.append(c)
match += c
logging.debug(f'{c} >> {openned} <{match}>')
elif c in pairs.values():
if len(openned) > 0:
if c == pairs[openned[-1]]:
del openned[-1]
match += c
logging.debug(f'{c} >> {openned} <{match}>')
if len(match) > 0 and len(openned) == 0:
results.append(match)
else:
match = str()
openned = list()
logging.debug(f'{c} ! {openned} <{match}>')
else:
if len(match) > 0 and len(openned) == 0:
results.append(match)
match = str()
openned = list()
logging.debug(f'{c} !! {openned} <{match}>')
if len(match) > 0:
results.append(match)
logging.debug(f'Matches: {results}')
results.sort(key=len)
if len(results) > 0:
return results[-1]
else:
return None
def test_str2(in_str: str) -> str:
match = [0] * (len(in_str) + 1)
for i in range(1, len(in_str)):
if in_str[i] in '({[':
continue
open = '({['[')}]'.index(in_str[i])]
start = i - 1 - match[i - 1]
if start < 0 or in_str[start] != open:
continue
match[i] = i - start + 1 + match[start - 1]
best = max(match)
end = match.index(best)
return in_str[end + 1 - best:end + 1]
print(test_str2(some_str))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment