Created
April 23, 2025 05:25
-
-
Save rjurney/fa8643a4e621aed22d4777dd938a50f1 to your computer and use it in GitHub Desktop.
Parse JSONIsh brackets
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: | |
openers = ["(", "{", "["] | |
closers = [")", "}", "]"] | |
valid = openers + closers | |
def __init__(self): | |
self.stack = [] | |
def push(self, x): | |
self.stack.append(x) | |
def pop(self): | |
if len(self.stack) > 0: | |
return self.stack.pop() | |
def isValid(self, s: str) -> bool: | |
if len(s) < 2: | |
return False | |
for c in s: | |
if c not in self.__class__.valid: | |
raise ValueError("Invalid character: '{c}'. Valid characters: '{valid}'.") | |
if c in self.__class__.openers: | |
self.push(c) | |
elif c in self.__class__.closers and (len(self.stack) == 0): | |
return False | |
else: # is closer | |
o = self.pop() | |
if c and o and (self.__class__.openers.index(o) != self.__class__.closers.index(c)): | |
print("Invalid character: '{c}' does not match '{o}'.") | |
return False | |
if len(self.stack) > 0: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment