TypeScript Nesting
function nesting(s: string): number {
if (s === "") {
return 1;
}
const stack: string[] = [];
for (const v of s) {
if (v === ")") {
if (stack.length === 0 || stack.pop() !== "(") {
return 0;
}
} else if (v) {
stack.push(v);
}
}
return stack.length === 0 ? 1 : 0;
}
This treats the string like a balance counter: open parentheses add one, closing ones remove one.