Skip to content

Instantly share code, notes, and snippets.

@alexwebgr
Created January 17, 2020 11:24
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 alexwebgr/5e8fe9d22d9edcb3a2d75e0761701130 to your computer and use it in GitHub Desktop.
Save alexwebgr/5e8fe9d22d9edcb3a2d75e0761701130 to your computer and use it in GitHub Desktop.
PARENS = {
"(" => ")",
"{" => "}",
"[" => "]"
}
OPENING_PARENS = PARENS.keys
CLOSING_PARENS = PARENS.values
def valid_parentheses(string)
stack = []
string.each_char do |ch|
if OPENING_PARENS.include?(ch)
stack << ch
elsif CLOSING_PARENS.include?(ch)
ch == PARENS[stack.last] ? stack.pop : (return false)
end
end
stack.empty?
end
p valid_parentheses("(){}[]") # true
p valid_parentheses("[(])") # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment