Skip to content

Instantly share code, notes, and snippets.

@rjurney
Created April 23, 2025 05:25
Show Gist options
  • Save rjurney/fa8643a4e621aed22d4777dd938a50f1 to your computer and use it in GitHub Desktop.
Save rjurney/fa8643a4e621aed22d4777dd938a50f1 to your computer and use it in GitHub Desktop.
Parse JSONIsh brackets
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