小黑代码 class Solution: def lengthOfLastWord(self, s: str) -> int: # 字符串长度 n = len(s) # 去除尾部空格 l = n-1 while l>=0 and s[l] == ' ': l -= 1 # 该字符串仅由空格组成 if l<0: return 0 # 开始计算单词长度 res = 0 while l>=0 and s[l] != ' ': res += 1 l -= 1 return res