Length of Last Word

题目地址:
https://leetcode.com/problems/length-of-last-word/description/
我的思路是去掉尾部所有空字符,然后计算count 直到遇到空字符为止

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s) == 0:
            return 0
        if len(s) == 1 and s==' ':
            return 0
        while s[-1] ==' ' and len(s) > 1:
            s = s[:-1]
        if len(s) == 0:
            return 0
        if len(s) == 1 and s==' ':
            return 0
        m = s[::-1]
        count = 0
        i = 0
        while i < len(m):
            if m[i] != ' ':
                count += 1
                i += 1
            else:
                break
        return count

你可能感兴趣的:(Length of Last Word)