跳过正文
  1. leetcode 题解/

58_最后一个单词的长度

·47 字·1 分钟

类型:字符串

    1. 最后一个单词的长度 💚

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

    ❓ 字符串 s 由若干个单词组成,单词间用空格分割,返回最后一个单词的长度。

    💡 逆向一次遍历

    由于我们要算最后一个单词的长度,直接从后往前遍历好了。

    class Solution:
        def lengthOfLastWord(self, s: str) -> int:
            count = 0
            for i in range(len(s) - 1, -1, -1):
                if s[i] != ' ':
                    count += 1
                elif count > 0:
                    return count
            return count

    时间复杂度:O(n),空间复杂度:O(1)