PU Length of Last Word

Jan 01, 1970

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note:

  • A word is defined as a character sequence consists of non-space characters only.

For example,

  • Given s = "Hello World",
  • return 5.

C Solution 1:

int lengthOfLastWord(char* s) {
    if (!s || !*s) return 0;
    int len = strlen(s);
    int i;
    for (i = len - 1; i > -1 && s[i] == ' '; i--);
    if (i == -1) return 0;
    int j;
    for (j = i - 1; j > -1 && s[j] != ' '; j--);
    return i - j;
}

C Solution 2:

int lengthOfLastWord(char* s) {
    int res = 0;
    while (*s) {
        if (*s++ != ' ') res++;
        else if (*s && *s != ' ') res = 0;
    }
    return res;
}

Summary:

  • Solution 2 is so beautiful.

LeetCode: 58. Length of Last Word