Created
January 17, 2020 11:24
-
-
Save alexwebgr/5e8fe9d22d9edcb3a2d75e0761701130 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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