Created
May 13, 2019 12:34
-
-
Save deepakkumarnd/a5042179d4d0c9c8ac1046bc76606394 to your computer and use it in GitHub Desktop.
Valid braces
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
TOKENS = { '}' => '{', ')' => '(', ']' => '[' }.freeze | |
def valid_brace?(input) | |
stack = [] | |
valid = true | |
input.each_char do |c| | |
case c | |
when '(', '[', '{' then stack.push(c) | |
when ')', ']', '}' then valid = (stack.pop == TOKENS[c]) | |
else | |
valid = false | |
end | |
break unless valid | |
end | |
valid && stack.empty? | |
end | |
inputs = ['()[]{}', '([{}])', '[({})](]', '[(])', '(}'] | |
inputs.each do |input| | |
text = valid_brace?(input) ? "valid" : "invalid" | |
puts "#{input} is #{text}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment