We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defis_balanced(expression)exp_stack=[]# Stack in ruby can be created using an array# Related stack functions are Array#push, Array#pop, Array#last# Array#push appends an element to the array# Array#pop removes and returns last element in the array# Array#last returns the last element in the arrayexpression.eachdo|char|ifchar=='{'exp_stack.push('}')elsifchar=='['exp_stack.push(']')elsifchar=='('exp_stack.push(')')elseif(exp_stack.empty?||char!=exp_stack.last)returnfalseendexp_stack.popendendreturnexp_stack.empty?end
Stacks: Balanced Brackets
You are viewing a single comment's thread. Return to all comments →
Awesome technique, here's a ruby implementation