LeetCode 题解工作台
字符串中的单词数
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。 示例: 输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们将字符串 按照空格进行分割,然后统计不为空的单词个数。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
解题思路
方法一:字符串分割
我们将字符串 按照空格进行分割,然后统计不为空的单词个数。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def countSegments(self, s: str) -> int:
return len(s.split())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates a clear understanding of how to handle spaces and non-space characters in the string.
- question_mark
Candidate uses an efficient strategy to avoid unnecessary operations, such as splitting on all spaces.
- question_mark
Candidate can explain how to optimize for edge cases, such as leading, trailing, or multiple spaces.
常见陷阱
外企场景- error
Not handling leading or trailing spaces correctly, which might lead to inaccurate segment counts.
- error
Forgetting to exclude empty segments when splitting the string, especially when multiple spaces are used.
- error
Using inefficient methods like repeatedly scanning the string for spaces instead of processing the string in a single pass.
进阶变体
外企场景- arrow_right_alt
The input string contains leading or trailing spaces.
- arrow_right_alt
The input string contains multiple consecutive spaces.
- arrow_right_alt
The input string is empty or consists only of spaces.