Skip to content

Latest commit

 

History

History
69 lines (55 loc) · 2.01 KB

58. Length of Last Word.md

File metadata and controls

69 lines (55 loc) · 2.01 KB

1. Description

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note:

A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

2. Solutions

Solution 1: Language: C Two Pointers

From the end of the string, the first pointer tries to find the first non-space character, and the second pointer tries to find the next space to locate the last word.

  • Thursday, 27 August, 2020
  • Time Complexity: $O(n)$
  • Space Complexity: $O(1)$
  • Runtime: 0 ms, faster than 100.00% of C online submissions for Length of Last Word.
  • Memory Usage: 5.8 MB, less than 19.22% of C online submissions for Length of Last Word.
int lengthOfLastWord(char *s) {
    // First case: the string is empty; no word inside.
    if (*s == NULL) {
        return 0;
    }
    // An index points to the last character in string (not '\0');
    int end = strlen(s) - 1;
    // Then, we move the above index to point at the last "meaningful" character.
    while (s[end] == ' ' && end > 0) {
        end--;
    }
    // From the end index, we move a new index called "start" to the left to
    // find the first "meaningless" character, which should be a space. If it
    // does not exist, which means that there is no space between s[0] and
    // s[end], we should return end + 1, the length of the "last word".
    int start = end;
    while (s[start] != ' ' && start > 0) {
        start--;
    }
    if (s[start] != ' ') {
        return end + 1;
    }
    return end - start;
}

3. Testing Errors

  • Here are some "interesting" testing cases:
    • "";
    • " ";
    • " ";
    • "a ";
    • "abcdefg";
    • "Hello world";
    • " Hello world";
    • " Hello world ";