Last active
July 12, 2017 08:59
-
-
Save eliotsykes/cb864868f4462db90b46859452cf5a33 to your computer and use it in GitHub Desktop.
Ruby Bracket Validator
This file contains 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 'set' | |
def is_valid(code) | |
openers_to_closers = { | |
'(' => ')', | |
'{' => '}', | |
'[' => ']' | |
} | |
openers = Set.new(openers_to_closers.keys.to_set) | |
closers = Set.new(openers_to_closers.values.to_set) | |
openers_stack = [] | |
for i in 0...code.length | |
char = code[i] | |
if openers.include? char | |
openers_stack.push(char) | |
elsif closers.include? char | |
if openers_stack.empty? | |
return false | |
else | |
last_unclosed_opener = openers_stack.pop | |
# if this closer doesn't correspond to the most recently | |
# seen unclosed opener, short-circuit, returning false | |
if openers_to_closers[last_unclosed_opener] != char | |
return false | |
end | |
end | |
end | |
end | |
return openers_stack == [] | |
end |
This file contains 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 'set' | |
# 2-space indents conventional in Ruby | |
# Predicate methods conventionally end with a question mark | |
# (often without a is_/has_-prefix). | |
def valid?(code) | |
openers_to_closers = { | |
'(' => ')', | |
'{' => '}', | |
'[' => ']' | |
} | |
openers = openers_to_closers.keys.to_set | |
closers = openers_to_closers.values.to_set | |
openers_stack = [] | |
# Conventionally each is favored over for loops (thought to be a readability improvement) | |
code.chars.each do |char| | |
if openers.include? char | |
openers_stack.push(char) | |
elsif closers.include? char | |
return false if openers_stack.empty? | |
last_unclosed_opener = openers_stack.pop | |
# if this closer doesn't correspond to the most recently | |
# seen unclosed opener, short-circuit, returning false | |
return false if openers_to_closers[last_unclosed_opener] != char | |
end | |
end | |
openers_stack.empty? | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment