Length of Last Word

Easystring
Category: Fundamentals

Approach

Length of Last Word

Problem Statement

Given a string s consisting of words and 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:

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.

Approach

Right-to-Left Scan

Scan from right, skip trailing spaces, count word length.

Algorithm:

  1. Start from end of string
  2. Skip trailing spaces
  3. Count characters until space or start
  4. Return count

Complexity

  • Time: O(n)
  • Space: O(1)

Solution

java
1class Solution {
2    public int lengthOfLastWord(String s) {
3        int i = s.length() - 1;
4        
5        // Skip trailing spaces
6        while (i >= 0 && s.charAt(i) == ' ') {
7            i--;
8        }
9        
10        // Count word length
11        int length = 0;
12        while (i >= 0 && s.charAt(i) != ' ') {
13            length++;
14            i--;
15        }
16        
17        return length;
18    }
19}
Loading visualizer...