LeetCode 58. Length of Last Word

Post by ailswan Sep.03, 2023

58. Length of Last Word

Problem Statement

link: https://leetcode.com/problems/length-of-last-word/description/ https://leetcode.cn/problems/length-of-last-word/description/

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.

Example:

Input: "Hello World" Output: 5

Input: ` fly me to the moon ` Output: 4

Input: "luffy is still joyboy" Output: 6

Solution Approach

The solution involves trimming trailing spaces and identifying the last word in the string to measure its length.

Algorithm

  1. Trimming: Remove any leading or trailing spaces from the string using the strip() method.
  2. Splitting: Break the string into words using the split(“ “) method.
  3. Last Word Length: Retrieve the last word from the split list and return its length using the len() function.

Implement

    class Solution:
      def lengthOfLastWord(self, s: str) -> int:
          s = s.strip()
          w = s.split(" ")[-1]
          return len(w)