β¨ Basic : validity check using stack
const stack = [];
for (const ch of str) {
if (ch === "(") {
stack.push(ch);
} else {
const pop = stack.pop();
if (pop !== "(") return false;
}
return stack.length === 0;
}
π‘ Tips
For valid parentheses,
- The number of open parentheses
(
(str[0:i]
)- should be equal or greater than the number of close parentheses
)
.
- should be equal or greater than the number of close parentheses
- The number of close parentheses
)
(str[0:i]
)- can not be greater than the number of open parentheses
(
. - If so, it's invalid parentheses at index
i
(str[0:i]
).
- can not be greater than the number of open parentheses