Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.