Created
October 18, 2011 22:29
-
-
Save devth/1296936 to your computer and use it in GitHub Desktop.
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
def brackets_valid?(str) | |
open = [] | |
matches = { '{' => '}', '(' => ')', '[' => ']' } | |
str.split('').each do |c| | |
if matches.keys.include? c # it's an opening bracket | |
open.push c | |
elsif matches.values.include? c # it's a closing bracket | |
# must close the last open bracket | |
return false unless c == matches[open.pop] | |
end | |
end | |
true | |
end | |
def check(str) | |
puts brackets_valid?(str) ? "Valid" : "Invalid" | |
end | |
check("{}") | |
check("{{)") | |
check("{ code goes here }") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment