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
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 | class Solution { |