Created
October 13, 2014 16:05
-
-
Save jin/2c8b0c892f04aed76bfe to your computer and use it in GitHub Desktop.
Check for matching brackets in a string
This file contains hidden or 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 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