Skip to content

Instantly share code, notes, and snippets.

@hwine
Created January 12, 2016 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hwine/ae289ed4f1afbb79b145 to your computer and use it in GitHub Desktop.
Save hwine/ae289ed4f1afbb79b145 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
stack = []
matches = {
# open -> close
'(': ')',
'{': '}',
'[': ']',
}
open_chars = matches.keys()
close_chars = matches.values()
def check_string(s):
stack = []
for c in s:
if c in open_chars:
# push what it should match
stack.append(matches[c])
elif c in close_chars:
try:
should_match = stack.pop()
except IndexError:
# unbalanced
return "NO"
if c != should_match:
# bad match, we're done
return "NO"
if len(stack) == 0:
return "YES"
else:
# unbalanced
return "NO"
samples = [ "{}[]()", "{[}]" ]
samples = [
"[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]{",
"[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]]",
"[{()([)}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]",
"{}[]()",
"{[}]"
]
answers = []
for s in samples:
answers.append(check_string(s))
print repr(answers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment