A few ways in JavaScript


  • 0

    The long way:

    var lengthOfLastWord = function(s) {
        let len = 0;
        let hasStarted = false;
        for (let i = s.length - 1; i >= 0; i--) {
            if (s[i] !== ' ') hasStarted = true;
            if (hasStarted) {
                if (s[i] === ' ') break;
                len++;
            }
        }
        return len;
    };
    

    Shorter with trim and lastIndexOf:

    var lengthOfLastWord = function(s) {
        s = ' ' + s.trim();
        return s.length - s.lastIndexOf(' ') - 1;
    };
    

    And with trim and split:

    var lengthOfLastWord = function(s) {
        const arr = s.trim().split(' ');
        return arr[arr.length - 1].length;
    };
    

    Shortest with regex:

    var lengthOfLastWord = function(s) {
        return (s.match(/(\w+)\s*$/) || [, ''])[1].length;
    };
    

Log in to reply
 

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