How to Find the Length of the Last Word in a String: Python Solution for Leetcode.

ยท

2 min read

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

  1. Trim Leading and Trailing Spaces: Use strip() to remove any extra spaces at the beginning or end of the string.

  2. Split the String: Use split(" ") to divide the trimmed string into a list of words.

  3. Retrieve the Last Word: Access the last element of the list using [-1].

  4. 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)$$
    The strip() and split() operations both require traversing the string once, making the complexity linear with respect to the string's length.

  • Space complexity:
    $$O(k)$$
    The split() 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. ๐Ÿ˜Š


Did you find this article valuable?

Support VISHWANATH'S BLOG by becoming a sponsor. Any amount is appreciated!

ย