Leetcode 58. Length of Last Word

Problem Description

In this problem, we are given a string s that consists of upper/lower-case alphabets and empty space characters. Our task is to return the length of the last word in the string. If the last word does not exist, we should return 0.

A word, in this context, is defined as a character sequence that consists of non-space characters only.

Example Walkthrough

Let's consider an example for a better understanding of the problem.

Given string: "Hello World"

In this string, the last word is "World" and its length is 5. So, the output should be 5.

Solution Approach

To solve this problem, we will traverse backwards from the end of the string, ignoring the trailing spaces if any. We continue moving backward until we encounter the next space character which marks the end of the last word. The distance between this space character and the end of the string will give us the length of the last word.

Solution in Python

1
2python
3class Solution:
4    def lengthOfLastWord(self, s: str) -> int:
5        # Split the string into words
6        words = s.split()
7
8        # If no words are present, return 0
9        if not words:
10            return 0
11
12        # Return length of the last word
13        return len(words[-1])

Solution in Java

1
2java
3public class Solution {
4    public int lengthOfLastWord(String s) {
5        // Remove trailing spaces
6        s = s.trim();
7
8        // Get the last index of space in the string
9        int lastIndex = s.lastIndexOf(" ");
10
11        // Return the length of the last word
12        return s.length() - lastIndex - 1;
13    }
14}

Solution in Javascript

1
2javascript
3var lengthOfLastWord = function(s) {
4    // Split the string into words
5    var words = s.trim().split(" ");
6
7    // Return the length of the last word
8    return words[words.length - 1].length;
9};

Solution in C++

1
2c++
3class Solution {
4public:
5    int lengthOfLastWord(string s) {
6        int i = s.length() - 1;
7
8        while (i >= 0 && s[i] == ' ')
9            --i;
10        const int lastIndex = i;
11        while (i >= 0 && s[i] != ' ')
12            --i;
13
14        return lastIndex - i;
15    }
16};

Solution in C#

1
2csharp
3public class Solution {
4    public int LengthOfLastWord(string s) {
5        // Trim the trailing spaces
6        s = s.Trim();
7
8        // Get the last index of space in the string
9        int lastIndex = s.LastIndexOf(' ');
10
11        // Return the length of the last word
12        return s.Length - lastIndex - 1;
13    }
14}

Interpretation of Solutions

In all the solutions, we follow a common approach. First, we ignore any trailing space characters in the string. Then, we try to find the index of the last space character. The length of the last word is then calculated as the difference between the string length and the index of the last space character (incremented by 1 due to index starting from 0).

In Python, Java, C#, and JavaScript, we make use of built-in string functions to split the string into words and then determine the length of the last word. We use "split()" to divide the string into words, "-1" to access the last word and "len()" / ".length" to get the length of the word in Python and JavaScript, respectively. In Java and C#, we use "trim()" to remove trailing spaces, "lastIndexOf()" to get the last occurrence of the space character, and then subtract the index from the string length to get the length of the last word.

In the C++ solution, instead of using string functions, we start from the end of the string and manually search for the last word by checking all characters until we find a space or reach the beginning of the string. From there, we calculate the length of the last word as the difference between the current position and the end position.

Conclusion

This problem tests your understanding of string manipulation and basic algorithmic skills. Being able to solve this problem ensures you have a good understanding of how to handle strings and traverse them effectively in several programming languages. Good practices include using built-in functions where applicable to write cleaner and more readable code.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫