Advertisement
kai-rocket

Valid Parentheses

Apr 7th, 2021
664
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement