Leetcode 58.最后一个单词的长度(Python3)

58.最后一个单词的长度

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

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

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

示例:

输入: "Hello World"
输出: 5

代码:

#length-of-last-word
class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.strip()
        sum = ''
        for i in s:
            if i == ' ':
                sum = ''
            else:
                sum += i
        return len(sum)

利用python特征的代码:

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int        """
        strList = s.split()
        if strList:
            return len(strList[-1])
        return 0

思路:

1.去掉末尾空格

2.计数:记录最后一组的数量

链接:

https://leetcode-cn.com/problems/length-of-last-word/

猜你喜欢

转载自blog.csdn.net/qq_38575545/article/details/85030745
今日推荐