Skip to content

Instantly share code, notes, and snippets.

@devth
Created October 18, 2011 22:29
Show Gist options
  • Save devth/1296936 to your computer and use it in GitHub Desktop.
Save devth/1296936 to your computer and use it in GitHub Desktop.
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