解题思路
本题的思路是从后到前遍历,从第一个不为空格的数起,遇到再空格止。计数返回即可
代码
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ last_num = 0 length = len(s) if s == 0: return last_num else: for i in range(length-1,-1,-1): if s[i] != " ": last_num += 1 if s[i] == " " and last_num != 0: break return last_num