Valide Parentheses
/** * @param {string} s * @return {boolean} */ var isValid = function(s) { if(s.length%2!==0){return false}; let leftActers = ["(","{","["], rightActers = [")","}","]"], index = 0, key = 0, stack = []; let position = null; this.check = (elem)=>{ if(leftActers.includes(elem)){ console.log(elem); position = leftActers.indexOf(elem); stack.push(position); index++; key++; return check(s[key]); } if(elem===rightActers[stack[stack.length-1]]){ console.log(elem); stack.pop(); index--; key++; if(stack.length===0&&index===0&&s[key]===undefined){return true} else{return check(s[key])} } else{ return false; } } return check(s[key]); }; console.log(isValid("{()()}()"));
Published 23 Apr 2017