?? Solved A Fun LeetCode Problem: Length of the Last Word ??

Problem statement: https://leetcode.com/problems/length-of-last-word/description/

Given a string of words and spaces, we need to figure out the length of the last word. Sounds simple, right? But here's the catch—spaces can be tricky! ???

Let's break it down:

1?? First, we ignore any trailing spaces (because spaces aren't part of a word!).

2?? Then, starting from the end, we move backward and count characters until we hit another space—marking the start of the last word.

Example:

- For input "Hello World", the last word is "World", and its length is 5! ????

- For input " fly me to the moon ", after skipping trailing spaces, the last word is "moon", and its length is 4! ??

Here's my approach in Python ??:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        #ignore any trailing spaces
        n = len(s) - 1 #last index of string
        if s[n] == ' ': #if the end of string if a group of spaces, avoid it
            while s[n] == ' ':
                n -= 1
        ans = 0
        #starting from the end, we move backward and count characters until we hit       another space
        for i in range(n, -1, -1): #start from the end index where the char is non-space
            if s[i] == ' ': break #detect the boundary of the last word
            # print(s[i])
            ans += 1 #measure the length of the last word
        return ans        

?? The key idea is to move backward through the string until we find a word, making sure to skip any pesky spaces at the end! ??

要查看或添加评论,请登录

Rukshar A.的更多文章

社区洞察

其他会员也浏览了