Given a string of the brackets ()[]{}, return true if every bracket is closed by the same type in the correct order.
Push each opening bracket. A closing bracket must match the top of the stack. At the end, the stack must be empty.
1function isValid(s: string): boolean {2const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };3const stack: string[] = [];4for (const ch of s) {5if (!(ch in pairs)) stack.push(ch);6else if (stack.pop() !== pairs[ch]) return false;7}8return stack.length === 0;9}
Empty stack.
Space: play/pause · ←/→: step