SHARE
TWEET

Untitled

a guest Jul 21st, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # '(', '{', '[' are called "openers."
  2. # ')', '}', ']' are called "closers."
  3. # Write an efficient function that tells us whether or not an input string's openers and closers are properly nested.
  4.  
  5. # Examples:
  6.  
  7. # "{ [ ] ( ) }" should return True
  8. # "{ [ ( ] ) }" should return False
  9. # "{ [ }" should return False
  10.  
  11.  
  12.  
  13. def is_valid code
  14.   openers_to_closers = {
  15.         '(' => ')',
  16.         '{' => '}',
  17.         '[' => ']',
  18.   }
  19.   openers = openers_to_closers.keys
  20.   closers = openers_to_closers.values
  21.   openers_stack = []
  22.   code.split('').each do |char|
  23.     if openers.include? char
  24.       openers_stack << char
  25.     else
  26.       if openers_stack.empty?
  27.         return false
  28.       else
  29.         lastest_pushed_to_stack = openers_stack.pop()
  30.         if !(openers_to_closers[lastest_pushed_to_stack] == char)
  31.           return false
  32.         end
  33.       end
  34.     end
  35.   end
  36.   return openers_stack == []
  37. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top