Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Length of Last Word - Solution/C++

8. Length of Last Word

Question:

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

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

Example:

Input: s = "Hello World"
Output: 5

Input: s = " "
Output: 0

Constraints:
  • 1 <= s.length <= 10^4
  • s consists of only English letters and spaces ' '
  • .

    Source code

    Version 1

    Idea:
    This problem took me a lot of time thinking how to solve, because I tried many methods based on scanning string in order. As a result, I ingorned tailing spaces situation, e.g., "a " or "a bc ".
    Obviously, my logic was error! Finally, I refered to Huahua's Tech Road, the solution is very understandable, it scan the string in reverse order until a space or reach the beginning of the string.
    So, the first while(i >= 0 && s[i] == ' ') means trimming off space at tail; the second while(i >= 0 && s[i] != ' ') means calculating length of a last word.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Solution {
    public:
    int lengthOfLastWord(string s) {
    int i = s.length() - 1;
    int characters = 0;
    while(i >= 0 && s[i] == ' ') i--;
    while(i >= 0 && s[i] != ' '){
    i--;
    characters ++;
    }
    return characters;
    }
    };