In [1]:
class Solution:
def lengthOfLastWord(self, s: str) -> int:
length = 0
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
In [2]:
sol = Solution()
print("Output is :- ",sol.lengthOfLastWord("Hello World"))
print("Output is :- ",sol.lengthOfLastWord(" fly me to the moon "))
print("Output is :- ",sol.lengthOfLastWord("luffy is still joyboy"))
Output is :- 5 Output is :- 4 Output is :- 6