Created
December 5, 2014 02:16
-
-
Save gbanis/6f952e4a45a46cb2466a to your computer and use it in GitHub Desktop.
Validate a string for matching opening and closing parentheses and brackets.
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
# 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