58. Length of the last word

Given a string containing only uppercase and lowercase letters and Spaces, return the length of its last word. If the last word does not exist, return 0. A word is a string of letters that does not contain any Spaces.

Example:

Input:"Hello World"Output: 5Copy the code
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        if not s:  # empty string
            return 0
        str = s.split(' ')  # Separate each word with a space
        for i in range(len(str) - 1.- 1.- 1) :# reverse check if the character is null
            ifstr[i] ! =' ':
                return len(str[i])
        return 0
Copy the code