smj007

Untitled

Jun 24th, 2023
1,513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. # 1
  2.  
  3. class Solution:
  4.     def isValid(self, s: str) -> bool:
  5.  
  6.         stack = []
  7.         mapping = {
  8.             "(" : ")",
  9.             "{" : "}",
  10.             "[" : "]"
  11.         }
  12.         for character in s:
  13.             if character in mapping:
  14.                 stack.append(character)
  15.             elif character in list(mapping.values()):
  16.                 if len(stack)==0 or (mapping[stack.pop()] != character):
  17.                     return False
  18.  
  19.         if len(stack)>0:
  20.             return False
  21.         else:
  22.             return True
  23.        
  24. # 2
  25. class Solution:
  26.     def isValid(self, string: str) -> bool:
  27.          
  28.             stack = []
  29.             mapping = {
  30.                 "}" : "{",
  31.                 ")" : "(",
  32.                 "]" : "["
  33.             }
  34.            
  35.             for s in string:
  36.                 if s in ["{", "(", "["]:
  37.                     stack.append(s)
  38.                 elif s in ["}", ")", "]"]:
  39.                     if len(stack) > 0 and stack[-1] == mapping[s]:
  40.                         stack.pop()
  41.                     else:
  42.                         return False
  43.                 else:
  44.                     continue
  45.                    
  46.             # return only if stack is empty
  47.             return (len(stack) == 0)
  48.  
  49. # 3
  50. # Didn't like the editorial. Skipping it.
Advertisement
Add Comment
Please, Sign In to add comment