HomeLeetcode58. Length of Last Word (String) - Leetcode Solutions

58. Length of Last Word (String) – Leetcode Solutions

Description:

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

To solve this problem, we need to find the length of the last word in a given string sss. The string sss consists of words separated by spaces. The key steps to solve this problem are:

  1. Trim any trailing spaces from the string.
  2. Split the string into a list of words.
  3. Return the length of the last word in the list.

Here is a step-by-step breakdown of the solution:

  1. Trim Trailing Spaces: Using the strip() method, we can remove any leading or trailing spaces from the string. This ensures that any spaces at the end do not affect our word detection.
  2. Split the String: Use the split() method to divide the string into a list of words. By default, split() divides the string by any whitespace and removes any empty strings from the result.
  3. Find the Last Word: The last word in the list will be the last element of the list.
  4. Return the Length: Use the len() function to find and return the length of the last word.
Python
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        # Step 1: Trim trailing and leading spaces
        s = s.strip()
        
        # Step 2: Split the string into words
        words = s.split()
        
        # Step 3: Get the last word in the list
        last_word = words[-1]
        
        # Step 4: Return the length of the last word
        return len(last_word)

# Examples to test the function
solution = Solution()
print(solution.lengthOfLastWord("Hello World"))          # Output: 5
print(solution.lengthOfLastWord("   fly me   to   the moon  "))  # Output: 4
print(solution.lengthOfLastWord("luffy is still joyboy"))  # Output: 6

Explanation:

  1. strip(): This method removes any leading and trailing whitespace characters from the string.
  2. split(): This method splits the string into a list of words based on whitespace. For example, "Hello World" becomes ["Hello", "World"].
  3. words[-1]: This accesses the last element of the list words.
  4. len(last_word): This computes the length of the last word in the list.

Solution in Javascript:

JavaScript
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    // Step 1: Trim leading and trailing spaces
    s = s.trim();
    
    // Step 2: Split the string into words
    let words = s.split(/\s+/);
    
    // Step 3: Get the last word in the list
    let lastWord = words[words.length - 1];
    
    // Step 4: Return the length of the last word
    return lastWord.length;
};

// Examples to test the function
console.log(lengthOfLastWord("Hello World"));          // Output: 5
console.log(lengthOfLastWord("   fly me   to   the moon  "));  // Output: 4
console.log(lengthOfLastWord("luffy is still joyboy"));  // Output: 6

Solution in Java:

Java
class Solution {
    public int lengthOfLastWord(String s) {
        // Step 1: Trim leading and trailing spaces
        s = s.trim();
        
        // Step 2: Split the string into words
        String[] words = s.split("\\s+");
        
        // Step 3: Get the last word in the list
        String lastWord = words[words.length - 1];
        
        // Step 4: Return the length of the last word
        return lastWord.length();
    }

    // Main method for testing the function
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.lengthOfLastWord("Hello World"));          // Output: 5
        System.out.println(solution.lengthOfLastWord("   fly me   to   the moon  "));  // Output: 4
        System.out.println(solution.lengthOfLastWord("luffy is still joyboy"));  // Output: 6
    }
}

Solution in C#:

C#
public class Solution {
    public int LengthOfLastWord(string s) {
        // Step 1: Trim leading and trailing spaces
        s = s.Trim();
        
        // Step 2: Split the string into words
        string[] words = s.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        
        // Step 3: Get the last word in the list
        string lastWord = words[words.Length - 1];
        
        // Step 4: Return the length of the last word
        return lastWord.Length;
    }
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular