Length of Last Word - LeetCode Solution in C++, Java, Python

1. Introduction

The "Length of Last Word" problem focuses on finding the length of the last word in a given string, where a word is defined as a maximal substring consisting solely of non-space characters.

2. Problem

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.

3. Solution in C++

int lengthOfLastWord(string s) {
    int length = 0, tail = s.length() - 1;
    while (tail >= 0 && s[tail] == ' ') tail--; // Skip trailing spaces
    while (tail >= 0 && s[tail] != ' ') {
        length++;
        tail--;
    }
    return length;
}

Explanation:

1. Start from the end of the string and skip any trailing spaces.

2. Then, count the characters until the next space or the start of the string is reached.

3. The count at this point is the length of the last word.

4. Solution in Java

public int lengthOfLastWord(String s) {
    int length = 0, tail = s.length() - 1;
    while (tail >= 0 && s.charAt(tail) == ' ') tail--; // Skip trailing spaces
    while (tail >= 0 && s.charAt(tail) != ' ') {
        length++;
        tail--;
    }
    return length;
}

Explanation:

1. Begin from the end of s and move backwards, skipping any spaces.

2. Count the number of non-space characters until a space is encountered or the beginning of the string is reached.

3. The total count gives the length of the last word.

5. Solution in Python

def lengthOfLastWord(s):
    return len(s.rstrip().split(' ')[-1])

Explanation:

1. Use rstrip() to remove any trailing spaces from the string.

2. Split the string into words using split(' ').

3. Return the length of the last word in the list ([-1] index).


Comments