Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 7, 2024 00:22
Show Gist options
  • Save hongtaoh/bcf297ca3bdecaa30f1a9d71da8f225e to your computer and use it in GitHub Desktop.
Save hongtaoh/bcf297ca3bdecaa30f1a9d71da8f225e to your computer and use it in GitHub Desktop.
Solution to Leetcode 20 Valid Parentheses
class Solution:
def isValid(self, s: str) -> bool:
dic = {"(":")", "{":"}", "[":"]"}
stack = []
# we know all char in s is either key or value in dic
for i in s:
# if key, store in stack
if i in dic:
stack.append(i)
# if value, check whether there is corresponding key
elif len(stack)== 0 or dic[stack.pop()] != i:
return False
# e.g., when s = "["
return not stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment