How to Find the Length of the Last Word in a String: Python Solution for Leetcode.
Intuition
The problem requires finding the length of the last word in a string. A word is a sequence of non-space characters. My first thought was to remove any extra spaces from the input, split the string into words, and return the length of the last word. Using Python's built-in string methods simplifies this process significantly.
Approach
Trim Leading and Trailing Spaces: Use
strip()
to remove any extra spaces at the beginning or end of the string.Split the String: Use
split(" ")
to divide the trimmed string into a list of words.Retrieve the Last Word: Access the last element of the list using
[-1]
.Calculate Length: Use
len()
to get the length of the last word.
This approach ensures that we handle edge cases, such as strings with only spaces, and simplifies the logic using Python's robust string manipulation methods.
Complexity
Time complexity:
$$O(n)$$
Thestrip()
andsplit()
operations both require traversing the string once, making the complexity linear with respect to the string's length.Space complexity:
$$O(k)$$
Thesplit()
method creates a list of words, which takes additional space proportional to the number of words in the string.
Code
class Solution(object):
def lengthOfLastWord(self, s):
return len(s.strip().split(" ")[-1])
Connect with Me
If you found this solution helpful, feel free to connect with me on LinkedIn! Let's grow and share knowledge together. ๐