Created
July 2, 2022 03:05
-
-
Save wanderindev/82e7b3172d9d6ab18e9230ad6c857f71 to your computer and use it in GitHub Desktop.
This file contains 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(object): | |
def is_valid(self, s): | |
""" | |
:type s: str | |
:rtype: bool | |
""" | |
bracket_map = {")": "(", "]": "[", "}": "{"} | |
stack = [] | |
for bracket in s: | |
if bracket in bracket_map: | |
if stack and stack[-1] == bracket_map[bracket]: | |
stack.pop() | |
else: | |
return False | |
else: | |
stack.append(bracket) | |
return not stack | |
# Test cases | |
sol = Solution() | |
assert sol.is_valid("()") | |
assert sol.is_valid("()[]{}") | |
assert not sol.is_valid("(]") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment