JavaScript Solution


  • 0
    P
    var lengthOfLastWord = function(s) {
        let len = s.length;
        let foundNonSpaceChar =  false;
        let lastWhiteSpaceIdx =  len;
        let secondLastWhiteSpace =  -1;
        
        for( let i =  len-1; i>=0; i--){
            let char = s.charAt(i);
            
            if( char != ' '){
                foundNonSpaceChar = true;
            }
            
            if( char == ' '){
                if( foundNonSpaceChar ){
                    secondLastWhiteSpace =  i;
                    break;
                }else{
                    lastWhiteSpaceIdx =  i;
                }
            }
        }
        return lastWhiteSpaceIdx - secondLastWhiteSpace - 1;
    };
    

Log in to reply
 

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