leetcode python 58. 最后一个单词的长度

https://leetcode-cn.com/problems/length-of-last-word/description/
我的理解是简单的字符串处理,直接对原字符串进行操作,先把尾部空格删去,再读取字符,直到遇到空格返回字符数量,还是要注意全为空格以及没有空格,还有下标不能越界。

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

大牛们用split直接把字符串分割了,效率更高。学到了。

你可能感兴趣的:(Leetcode)