Another 1ms C solution


  • 1
    G
    int lengthOfLastWord(char* s) {
        char *start = s;
        int length = 0;
        while(*s) {
            s++;
        }
        s--;
        while(*s == ' ') {
            s--;
        }
        while(*s != ' ' && (s >= start)){
            length++;
            s--;
        }
        return length;
    }
    

    It finds the null terminator, moves backwards, skipping any spaces. When it encounters the first letter, it begins counting until it reaches either the beginning of the string or a space.


Log in to reply
 

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