LeetCode 题解工作台

最后一个单词的长度

给你一个字符串 s ,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。 单词 是指仅由字母组成、不包含任何空格字符的最大 子字符串 。 示例 1: 输入: s = "Hello World" 输出: 5 解释: 最后一个单词是“World”,长度为 5。 示例 2: …

category

1

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们从字符串 末尾开始遍历,找到第一个不为空格的字符,即为最后一个单词的最后一个字符,下标记为 。然后继续向前遍历,找到第一个为空格的字符,即为最后一个单词的第一个字符的前一个字符,记为 。那么最后一个单词的长度即为 $i - j$。 时间复杂度 ,其中 为字符串 长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。

单词 是指仅由字母组成、不包含任何空格字符的最大子字符串

 

示例 1:

输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为 5。

示例 2:

输入:s = "   fly me   to   the moon  "
输出:4
解释:最后一个单词是“moon”,长度为 4。

示例 3:

输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为 6 的“joyboy”。

 

提示:

  • 1 <= s.length <= 104
  • s 仅有英文字母和空格 ' ' 组成
  • s 中至少存在一个单词
lightbulb

解题思路

方法一:逆向遍历 + 双指针

我们从字符串 ss 末尾开始遍历,找到第一个不为空格的字符,即为最后一个单词的最后一个字符,下标记为 ii。然后继续向前遍历,找到第一个为空格的字符,即为最后一个单词的第一个字符的前一个字符,记为 jj。那么最后一个单词的长度即为 iji - j

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i = len(s) - 1
        while i >= 0 and s[i] == ' ':
            i -= 1
        j = i
        while j >= 0 and s[j] != ' ':
            j -= 1
        return i - j
speed

复杂度分析

指标
时间complexity is O(n) in all approaches, where n is the length of the string, since each character is inspected at most once. Space complexity varies: O(n) for the split approach, O(1) for backward scanning or index tracking.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expectations of handling trailing spaces correctly.

  • question_mark

    Interest in string traversal without extra data structures.

  • question_mark

    Observation of O(1) space solutions for interview optimization.

warning

常见陷阱

外企场景
  • error

    Failing to ignore trailing spaces, leading to off-by-one errors.

  • error

    Using split blindly, which may allocate unnecessary memory.

  • error

    Counting spaces instead of word characters, miscalculating length.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the last word itself instead of its length.

  • arrow_right_alt

    Compute the length of the first word or any k-th word in a string.

  • arrow_right_alt

    Handle punctuation or non-letter characters as part of words.

help

常见问题

外企场景

最后一个单词的长度题解:String-driven solution … | LeetCode #58 简单