Skip to content

Instantly share code, notes, and snippets.

@samarthsewlani
Created February 22, 2021 07:58
Show Gist options
  • Save samarthsewlani/07490799a83317ac1fbcd7ddb9f6b1e7 to your computer and use it in GitHub Desktop.
Save samarthsewlani/07490799a83317ac1fbcd7ddb9f6b1e7 to your computer and use it in GitHub Desktop.
Valid Parentheses LeetCode Solution
class Solution:
def isValid(self, s: str) -> bool:
stack=["#"] # Initializing with a dummy character
for i in range(len(s)):
if s[i]=="(" or s[i]=="{" or s[i]=="[": # If opening bracket, push in stack
stack.append(s[i])
continue
if (s[i]==")" and stack[-1]=="(") or (s[i]=="}" and stack[-1]=="{") or (s[i]=="]" and stack[-1]=="["):
stack.pop()
else:
return False
if len(stack)!=1: # If stack is not empty
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment