I gave this a shot! Similar to yours, my approach was to split the string and track the expected closing parens in a separate array. I used the every method instead of a for...of loop which works nicely with the empty string case.
constisValid=function(str){constpairs={'(':')','[':']','{':'}'};constclosingParens=[];return[...str].every(validate);functionvalidate(char,i,arr){constisLastChar=i===arr.length-1;// If char found in pairs, push closing paren to arrif(pairs[char]&&!isLastChar){closingParens.push(pairs[char]);returntrue;}else{// If char has no closing paren, return falseif(!closingParens.length)returnfalse;// Check if current char is last in arrconstlastCharInArray=closingParens.pop();// If last char and unmatched parens, return falseif(isLastChar&&closingParens.length)returnfalse;// If pair found, continueif(char===lastCharInArray)returntrue;}}};
I gave this a shot! Similar to yours, my approach was to split the string and track the expected closing parens in a separate array. I used the
every
method instead of afor...of
loop which works nicely with the empty string case.What do you think?
For :"{[]}" it returns false.
Try solving it here : leetcode.com/problems/valid-parent...
@akhil I updated it to meet that condition!