Javascript 85ms solution

  • 0

    Simple and quick for loop that starts at the end of the string.
    If start equals 0 and the loop encounters a character that is not a space, start is now redefined as the index + 1
    (since the total amount of indexes === length - 1)
    This will catch edge cases where the string has no spaces.

    if the loop encounters another space, after start has been redefined from 0, the loop returns the current index - start -1 (To undo our edge case catch).

    If the loop runs through without encountering another non-space character, the function returns start.

    var lengthOfLastWord = function(s) {
        if(!s) return 0;
        let start = 0;
        for (let i = s.length - 1; i >= 0; i--) {
            let char = s[i];
            if(char !== ' ' && !start) start = i + 1;
            //Catches edge cases where string is a single word w/ no spaces
            if(char === ' ' && start) return start - i - 1; //Undoes edge case catch
        return start;

Log in to reply

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