Intuition
Walk backward from the end of the string. Skip any trailing spaces, then count characters until you hit the next space or the start — that count is the last word's length.
Explanation
Idea
The last word is at the tail of the string, possibly with trailing spaces after it. Scanning from the right finds it in one pass without splitting the whole string: first skip trailing spaces, then count the run of non-space characters.
Algorithm
- Start
iat the last index. Whiles[i]is a space, decrementi(skip trailing spaces). - Then, while
i >= 0ands[i]is not a space, increment alengthcounter and decrementi. - Return
length.
Worked example: " fly me to the moon "
- Skip the two trailing spaces → land on
n. - Count
n, o, o, m→ length 4; the next character is a space, stop.
Result: 4 (the word moon).
Complexity
- Time: O(n) worst case, but only touches the trailing spaces and last word.
- Space: O(1).
Implementation
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
int length = 0;
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}