LeetCode 题解工作台
最后一个单词的长度
给你一个字符串 s ,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。 单词 是指仅由字母组成、不包含任何空格字符的最大 子字符串 。 示例 1: 输入: s = "Hello World" 输出: 5 解释: 最后一个单词是“World”,长度为 5。 示例 2: …
1
题型
9
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们从字符串 末尾开始遍历,找到第一个不为空格的字符,即为最后一个单词的最后一个字符,下标记为 。然后继续向前遍历,找到第一个为空格的字符,即为最后一个单词的第一个字符的前一个字符,记为 。那么最后一个单词的长度即为 $i - j$。 时间复杂度 ,其中 为字符串 长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 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 <= 104s仅有英文字母和空格' '组成s中至少存在一个单词
解题思路
方法一:逆向遍历 + 双指针
我们从字符串 末尾开始遍历,找到第一个不为空格的字符,即为最后一个单词的最后一个字符,下标记为 。然后继续向前遍历,找到第一个为空格的字符,即为最后一个单词的第一个字符的前一个字符,记为 。那么最后一个单词的长度即为 。
时间复杂度 ,其中 为字符串 长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.