Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def is_valid(s)
- opening_to_closing = {
- "(" => ")",
- "[" => "]",
- "{" => "}"
- }
- final_stack = s.each_char.reduce(Array.new) do |stack, c|
- # If the current character is an opening char,
- # place it on top of the stack
- if opening_to_closing.has_key? c then
- stack.push(c)
- # otherwise if the stack is empty then we know that
- # there wil never be a match
- # same condition goes for if the current character's
- # opposite is not on the top of the stack
- elsif stack.empty? or not opening_to_closing[stack.pop()].eql? c then
- return false
- end
- # return the updated stack from the proc
- stack
- end
- # If, at the end the stack is empty, everything was matched
- return final_stack.empty?
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement