Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i=len(s)-1
while(s[i]==' 'and i>=0):
i-=1
j=i
while(s[j]!=' 'and j>=0):
j-=1
return i-j
filter spaces in the end and compute the last word’s length.
or
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split()[-1])



