I'm perplexed about the logic behind this function potentially returning true
. My understanding is that if an item is added to the stack
, then evaluating !stack.length
would yield false
, correct? It seems like there might be a gap in my knowledge regarding how stacks operate, as I can't seem to pinpoint where I've gone wrong.
var isValid = function (s) {
const hash = {
'(': ')',
'{': '}',
'[': ']',
};
const stack = [];
for (const char of s) {
if (char in hash) stack.push(char);
else {
const top = stack.pop();
if (top === undefined || hash[top] !== char) {
return false;
}
}
}
return !stack.length;
};