Advertisement
FrostByte404

Ruby solution for leetcode matching parenthesis problem

Aug 8th, 2022
1,715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.82 KB | None | 0 0
  1. def is_valid(s)
  2.     opening_to_closing = {
  3.         "(" => ")",
  4.         "[" => "]",
  5.         "{" => "}"
  6.     }
  7.    final_stack = s.each_char.reduce(Array.new) do |stack, c|
  8.        # If the current character is an opening char,
  9.        # place it on top of the stack
  10.        if opening_to_closing.has_key? c then
  11.            stack.push(c)
  12.         # otherwise if the stack is empty then we know that
  13.         # there wil never be a match
  14.         # same condition goes for if the current character's
  15.         # opposite is not on the top of the stack
  16.        elsif stack.empty? or not opening_to_closing[stack.pop()].eql? c then
  17.           return false
  18.        end
  19.         # return the updated stack from the proc
  20.         stack
  21.    end
  22.     # If, at the end the stack is empty, everything was matched
  23.     return final_stack.empty?
  24. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement