Created
October 7, 2024 00:22
-
-
Save hongtaoh/bcf297ca3bdecaa30f1a9d71da8f225e to your computer and use it in GitHub Desktop.
Solution to Leetcode 20 Valid Parentheses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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