kai-rocket

Valid Parentheses

Apr 7th, 2021
377
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution:
  2.     def isValid(self, s: str) -> bool:
  3.         # Use list to represent stack
  4.         stk = []
  5.        
  6.         # Loop through string
  7.         for c in s:
  8.             # If opening paren, push paren onto stack
  9.             if c == '(' or c == '[' or c == '{':
  10.                 stk.append(c)
  11.             # If closing paren
  12.             elif c == ')' or c == ']' or c == '}':
  13.                 # If stack is empty, return False
  14.                 if not stk:
  15.                     return False
  16.                 # If top elem on stack is matching open paren, pop open paren from stack
  17.                 if (c == ')' and stk[-1] == '(') or (c == ']' and stk[-1] == '[') or (c == '}' and stk[-1] == '{'):
  18.                     stk.pop()
  19.                 # Else, return False
  20.                 else:
  21.                     return False
  22.                
  23.         # If stack is empty return True, else return False
  24.         if not stk:
  25.             return True
  26.         return False
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×