patternrubyMinor
Balanced parenthesis in Ruby
Viewed 0 times
balancedrubyparenthesis
Problem
I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.
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:
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.
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
endThe 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.
Solution
To eliminate nested loop you may apply regex checking for invalid symbol from the start -- it would be O(n) + O(n) = O(n):
def balanced? string
return false if string.length.odd?
return false if string =~ /[^\[\]\(\)\{\}]/
pairs = { '{' => '}', '[' => ']', '(' => ')' }
stack = []
string.chars do |bracket|
if expectation = pairs[bracket]
stack << expectation
else
return false unless stack.pop == bracket
end
end
stack.empty?
endCode Snippets
def balanced? string
return false if string.length.odd?
return false if string =~ /[^\[\]\(\)\{\}]/
pairs = { '{' => '}', '[' => ']', '(' => ')' }
stack = []
string.chars do |bracket|
if expectation = pairs[bracket]
stack << expectation
else
return false unless stack.pop == bracket
end
end
stack.empty?
endContext
StackExchange Code Review Q#125321, answer score: 5
Revisions (0)
No revisions yet.