Approach

remove all hanging spaces, split the string into a list of words then just return the last index’s length

Code

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.rstrip()
        s = s.split(" ")
        return len(s[-1])