Skip to content

Instantly share code, notes, and snippets.

@jin
Created October 13, 2014 16:05
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 jin/2c8b0c892f04aed76bfe to your computer and use it in GitHub Desktop.
Save jin/2c8b0c892f04aed76bfe to your computer and use it in GitHub Desktop.
Check for matching brackets in a string
def check_string(str)
str.empty? || is_balanced(0, str)
end
def is_balanced(num_left_brackets, str)
if str.head == "["
is_balanced(num_left_brackets + 1, str.tail)
elsif str.head == "]"
return false if num_left_brackets == 0
is_balanced(num_left_brackets - 1, str.tail)
else
num_left_brackets == 0
end
end
# utility methods
class String
def head
self[0]
end
def tail
self[1..-1]
end
end
p check_string("[]") # true
p check_string("") # true
p check_string("[[]") # false
p check_string("[][]") # true
p check_string("]]]") # false
p check_string("[[[]]") # false
p check_string("][][][") # false
p check_string("[[[[]]][][][[]]]") # true
p check_string("[[[]][]]]][][][[]]]") # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment