Last active
May 30, 2018 20:00
-
-
Save absk1317/a2351d86fa3110506cc2f5866629ca7f to your computer and use it in GitHub Desktop.
String balance check whether for brackets
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
require 'pry' | |
PAIRS = { | |
'{' => '}', | |
'[' => ']', | |
'(' => ')' | |
}.freeze | |
def balanced?(string) | |
return false if string.length.odd? | |
return false if string =~ /[^\[\]\(\)\{\}]/ | |
stack = [] | |
push_and_pop string, stack | |
stack.empty? | |
end | |
def push_and_pop string, stack | |
string.chars do |bracket| | |
if expectation = PAIRS[bracket] | |
stack << expectation | |
else | |
return false unless stack.pop == bracket | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment