Leetcode刷题记录——58. 最后一个单词的长度

在这里插入图片描述

我们从数组的最后开始考虑
首先找到倒数第一个非空位置(若全空则返回0)
然后找倒数第二个非空位置
返回二者间距

class Solution:
    def lengthOfLastWord(self, s: str) -> int:

        if s == "":
            #print(list(set(s)))
            return 0
        length = len(s)
        if ' ' not in s:
            return length
        cur = length - 1
        while s[cur] == ' ':
            cur -= 1
            if cur == -1:
                return 0
        #start = cur
        res = 0
        while s[cur] != ' ':
            res += 1
            cur -= 1
        return res
发布了59 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/105480006