The Number of Weak Characters in the Game — stack
Push openers; a closer is legal only if it matches the current top. Built for LeetCode 1996. The Number of Weak Characters in the Game.
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 theNumberOfWeakCharactersInTheGame(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