58. Length of Last Word | LeetCode | Solution

Here is the link to the problem. See the full explanation on LeetCode first. Try to understand the problem. It’s an easy problem.

So the problem is, we have to return the length of the last word from the given string. The string can be consist of uppercase and lowercase letters and separated by a space.

Things to remember, we will return 0 if there is no last word in the given string. We can assume that it will be an empty string.

If there is only one word in the given string, we will return that word length. Because this is the only word, that is the first and last of the string at the same time.

Solution

To solve this problem, first, we split the string into a list and store it in a variable. We don’t need to use space as a separator. Python will do this for us.

After that, we will check the length of the list using len function. We will return 0 if there is no element in the list.

If the length of the list is not empty, we will return the last word length. To access the last element of a Python list we can use index -1.

Let’s see the full code below.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        
        str_arr = s.split()
        
        if len(str_arr) == 0:
            return 0
        else:
            return len(str_arr[-1])

If you submit the code in LeetCode, it will be accepted.