Length Of Last Word
Find how many letters the last word of a sentence has, even when spaces follow it.
Given a string s
Example 1
Output: 5
Explanation: the last word is "World", which has 5 letters.
Example 2
Output: 4
Explanation: the last word is "moon"; the two spaces after it do not count.
Example 3
Output: 6
The Idea
When you read a sentence, you find the last word without effort: your eye jumps to the end and picks out the final group of letters. In Example 1, that is "World", and its length is 5.
Example 2 is less tidy. The string " fly me to the moon "
It ends at the last character that is not a space, and it begins just after the space before that. Everything in front of that space has no effect on the answer. So there is no need to read the string from the start at all. Look at the picture below, where each dot is a space and the small numbers are the positions, or indexes, starting from 0.
Reading starts at index 26, on the right. The label "1. skip spaces at 26 and 25" marks the two spaces at the end of the string, called trailing spaces. They are passed over without counting. Next, "2. count n, o, o, m" counts the letters of "moon" from right to left, which gives 4. Then "3. stop at the space at index 20": a space means the word is over, so the answer is 4.
The grey part, marked "never read", holds most of the string. So the last word can be found by walking backwards in two phases: first past the spaces, then through the letters.
Solution Approach
Turning that idea into code means settling three things: whether Java's built-in string methods are good enough, how to walk past the trailing spaces, and when to stop counting.
Splitting the string into words
Could Java's string methods do the work? s.trim()split(" ")
Skipping the trailing spaces
How do we get from the end of the string to the last letter? Keep an index is.length() - 1iii
Counting the letters
When does the counting stop? Keep moving ii
That second way to stop matters when the last word is also the first, as in "a". There is no space in front of it, so without the check on icharAtStringIndexOutOfBoundsException
Java Solution
The method lengthOfLastWord
- First, set the index
to the last position of the string,i .s.length() - 1 - A first loop moves
left while it is still inside the string (i ) and the character ati >= 0 is a space. This passes over the trailing spaces.i - Then start a counter,
, at 0. A second loop moveslength left while it is inside the string and the character is not a space, adding 1 toi each time.length - When the second loop stops, return
, the number of letters it passed.length
Both loops test i >= 0s.charAt(i)&&charAt
The main
public class LengthOfLastWord {
public static int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') {
i--; // skip trailing spaces
}
int length = 0;
while (i >= 0 && s.charAt(i) != ' ') {
length++; // count the last word's letters
i--;
}
return length;
}
public static void main(String[] args) {
System.out.println(lengthOfLastWord("Hello World"));
System.out.println(lengthOfLastWord(" fly me to the moon "));
System.out.println(lengthOfLastWord("luffy is still joyboy"));
System.out.println(lengthOfLastWord("a")); // one word, no spaces
System.out.println(lengthOfLastWord("day ")); // one word, then spaces
System.out.println(lengthOfLastWord(" ")); // only spaces
}
}
Running it prints:
5
4
6
1
3
0
The 5, 4 and 6 at the top match the three examples. Look at the 4: the two spaces after "moon" were skipped, not counted. The 1 comes from "a", where the second loop ends because i
The 3 comes from "day ""Hello World "
The original implementation,
Complexity
The work is the two backward loops, and together they read each character at most once.
- Time: O(n) at worst, for a string of n characters. The loops only read the trailing spaces, the last word and the one space before it. That is all n characters only when the string is a single word or nearly all trailing spaces.
- Space: O(1), because the method keeps only the index
and the counteri . Thelength andtrim way needs O(n) extra space for the array of words.split
Walking over words from the end of a string also comes up in