classSolution:deflengthOfLastWord(self,s:str) ->int:ifnot s:return0 s = s.strip()#去除首尾空格 l = s.split(' ')#按空格切分returnlen(l[-1])#求最后一项长度
解法二:
从后往前遍历即可
classSolution:deflengthOfLastWord(self,s:str) ->int: s = s.strip()#去除首尾空格 n =len(s)if n ==0:return0 i = n -1 count =0#字符计数while i >=0and s[i]!=' ':#从后往前,遇到空格即退出 i -=1 count +=1return count