Advertisement
Abhisek92

parenthesis.py

May 4th, 2023
1,188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. class Solution(object):
  2.     def isValid(self, s: str) -> bool:
  3.         stack = list()
  4.         for chr in s:
  5.             if chr == '(':
  6.                 stack.append(1)
  7.             elif chr == '{':
  8.                 stack.append(2)
  9.             elif chr == '[':
  10.                 stack.append(3)
  11.             elif chr == ')':
  12.                 if len(stack) > 0 and stack[-1] == 1:
  13.                     stack.pop(-1)
  14.                 else:
  15.                     return False
  16.             elif chr == '}':
  17.                 if len(stack) > 0 and stack[-1] == 2:
  18.                     stack.pop(-1)
  19.                 else:
  20.                     return False
  21.             elif chr == ']':
  22.                 if len(stack) > 0 and stack[-1] == 3:
  23.                     stack.pop(-1)
  24.                 else:
  25.                     return False
  26.         return len(stack) == 0
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement