Skip to content

Instantly share code, notes, and snippets.

@gbanis
Created December 5, 2014 02:16
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 gbanis/6f952e4a45a46cb2466a to your computer and use it in GitHub Desktop.
Save gbanis/6f952e4a45a46cb2466a to your computer and use it in GitHub Desktop.
Validate a string for matching opening and closing parentheses and brackets.
# create a stack
# set the lookup hash
# set left = lookup.keys
# set right = lookup.values
# for each char in string
# is it a left bracket?
# add character on the stack
# if not, is it a right bracket?
# pop the last left bracket from the stack
# does it match to the current character? (right bracket)
# if it doesn't return false
# is the stack empty?
# return false
# is the stack empty?
# return true or false
def smarter_validate(str)
stack = []
lookup = { '(' => ')', '[' => ']', '{' => '}', '<' => '>' }
left = lookup.keys
right = lookup.values
str.each_char do |char|
if left.include? char
stack << char
elsif right.include? char
return false if stack.empty? || (lookup[stack.pop] != char)
end
end
return stack.empty?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment