Javascript use array as stack


  • 0
    S

    var isValid = function(s) {
    let arr=[],i,len,temp;
    len=s.length;
    for(i=0;i<len;i++){
    if("("==s[i] || "["==s[i] || "{"==s[i]){
    arr.push(s[i]);
    }else if(")"==s[i] || "]"==s[i] || "}"==s[i]){
    if(0==arr.length){
    return false;
    }else{
    temp = arr[arr.length-1];
    }
    switch(s[i]){
    case ")":
    if("("== temp) arr.pop();
    else return false;
    break;
    case "]":
    if("["== temp) arr.pop();
    else return false;
    break;
    case "}":
    if("{"== temp) arr.pop();
    else return false;
    break;
    }
    }else{
    return false;
    }
    }
    if( 0==arr.length )
    return true;
    else
    return false;
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.