I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.
def balanced?(string)
return false if string.length.odd?
pairs = { '{' => '}', '[' => ']', '(' => ')' }
string.chars.each_with_object([]) do |bracket, stack|
if pairs.keys.include?(bracket)
stack << bracket
elsif pairs.values.include?(bracket)
return false unless pairs[stack.pop] == bracket
else
return false
end
end
true
end
The first check is for the length of the string: If it's odd, the can't be balanced.
I then iterate over the chars of the string:
- If I find an opening bracket, I add it to an array.
- If I find a closing bracket, I remove the last element from the array and check if the brackets are a pair.
- If I find neither an opening or a closing bracket, the string must be invalid.
Are there any edge cases I'm missing? Also, this doesn't seem efficient: First, there's an added dictionary. Second, there is a linear search on each iteration to check either the keys or the values of the dictionary. There's an \$O(n)\$ on the array resulting from the string, as well, but I'm not sure if we can avoid this.
true
, I should check to see if the stack is empty. \$\endgroup\$