I'm trying to solve the Valid Parentheses, and as described in title, I can't figure how to Array.push to work in this context.
function isValidPar(par){
var stack = [];
var length = par.length;
for (var i=0; i<length; i++) {
var p = par[i];
if(p === "(" || p === "{" || p === "[") {
stack.push(p);
} else if(p === ")") {
if(stack.length === 0 || stack[stack.length-1] != "(") {return false}
stack.pop();
} else if(p === "]") {
if(stack.length === 0 || stack[stack.length-1] != "[") {return false}
stack.pop();
} else if(p === "}") {
if(stack.length === 0 || stack[stack.length-1] != "{") {return false}
stack.pop();
} return stack.length === 0;
}
}
If I console.log right after stack.push(), then it shows the element I just inserted. But when I try it anywhere else, like inside else if statements or before return, it seems like the array is empty.
returnstatement is one block too deep?forloop will have only one iteration because you've put areturnstatement at the end of it.