Problem#
Given a string s
consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Examples#
Example 1:
1
2
3
4
5
Input:
s = "Hello World"
Output:
5
Explanation: The last word is "World" with length 5.
Example 2:
1
2
3
4
5
Input:
s = " fly me to the moon "
Output:
4
Explanation: The last word is "moon" with length 4.
Example 3:
1
2
3
4
5
Input:
s = "luffy is still joyboy"
Output:
6
Explanation: The last word is "joyboy" with length 6.
Solution#
Method 1 - Split the string#
We can split the string, and count the characters in last word.
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.StringTokenizer;
public class Solution {
public int lengthOfLastWord (String s) {
StringTokenizer st = new StringTokenizer(s);
String lastWord = "" ;
while (st.hasMoreTokens ()) {
lastWord = st.nextToken ();
}
return lastWord.length ();
}
}
Time complexity:O(n+k)
n = length , k = no of words extracted
Space complexity:O(n)
as all the words are extracted and then iterated over
Method 2 - Count from behind 🏆#
We just need a flag to mark the start of letters from the end. If a letter starts and the next character is not a letter, return the length.
Video Explanation#
VIDEO
Dry Run#
Code#
Java
- Time Complexity:`o(n)` , as the Whole String Can Be One Sentence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int lengthOfLastWord (String s) {
int i = s.length () - 1;
//ignore trailing whitespace
// i will be -1 if whole string is white space
while (i >= 0 && s.charAt (i) == ' ' ){
i-- ;
}
int len = 0;
while (i >= 0 && s.charAt (i) != ' ' ) {
i-- ;
len++ ;
}
return len;
}
1
- Space complexity:`O(1)`