Check If Word Is Valid After Substitutions — stack
Push openers; a closer is legal only if it matches the current top. Built for LeetCode 1003. Check If Word Is Valid After Substitutions.
The stack is the nest of brackets that are still open. A mismatch or a leftover opener at the end is an immediate no.
Algorithm
- On an opener, push.
- On a closer, the top must be its partner — otherwise reject.
- Return true only if the stack is empty at the end.
- Time
- O(n)
- Space
- O(n)
class Solution: def checkIfWordIsValidAfterSubstitutions(self, s: str) -> bool: pairs = {")": "(", "]": "[", "}": "{"} stack: list[str] = [] for ch in s: if ch in pairs: if not stack or stack[-1] != pairs[ch]: return False stack.pop() else: stack.append(ch) return not stack