leetcode 解题 最后一个单词的长度

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

输入: "Hello World"
输出: 5

逆序循环,注意字符串末尾出现空格的情况

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

猜你喜欢

转载自blog.csdn.net/liziyun537/article/details/82828860