58. Length of Last Word
String ·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
- Trimming: Remove any leading or trailing spaces from the string using the strip() method.
- Splitting: Break the string into words using the split(“ “) method.
- 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)