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.

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

Examples

Example 1:

Input:
s = "Hello World"
Output:
 5
Explanation: The last word is "World" with length 5.

Example 2:

Input:
s = "   fly me to the moon  "
Output:
 4
Explanation: The last word is "moon" with length 4.

Example 3:

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.

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.

Dry Run

Code

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;
}
  • Time complexity:O(n) , as the whole string can be one sentence
  • Space complexity:O(1)