LeetCode 题解工作台
句子中的最多单词数
一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。 给你一个字符串数组 sentences ,其中 sentences[i] 表示单个 句子 。 请你返回单个句子里 单词的最多数目 。 示例 1: 输入: sentences = ["alice and bob l…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们遍历数组 `sentences`,对于每个句子,我们计算其中的空格数,那么单词数就是空格数加 。最后返回最大的单词数即可。 时间复杂度 ,其中 是数组 `sentences` 中所有字符串的长度之和。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。
给你一个字符串数组 sentences ,其中 sentences[i] 表示单个 句子 。
请你返回单个句子里 单词的最多数目 。
示例 1:
输入:sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] 输出:6 解释: - 第一个句子 "alice and bob love leetcode" 总共有 5 个单词。 - 第二个句子 "i think so too" 总共有 4 个单词。 - 第三个句子 "this is great thanks very much" 总共有 6 个单词。 所以,单个句子中有最多单词数的是第三个句子,总共有 6 个单词。
示例 2:
输入:sentences = ["please wait", "continue to fight", "continue to win"] 输出:3 解释:可能有多个句子有相同单词数。 这个例子中,第二个句子和第三个句子(加粗斜体)有相同数目的单词数。
提示:
1 <= sentences.length <= 1001 <= sentences[i].length <= 100sentences[i]只包含小写英文字母和' '。sentences[i]的开头和结尾都没有空格。sentences[i]中所有单词由单个空格隔开。
解题思路
方法一:空格计数
我们遍历数组 sentences,对于每个句子,我们计算其中的空格数,那么单词数就是空格数加 。最后返回最大的单词数即可。
时间复杂度 ,其中 是数组 sentences 中所有字符串的长度之和。空间复杂度 。
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return 1 + max(s.count(' ') for s in sentences)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n*m) where n is the number of sentences and m is the average length of a sentence. Space complexity is O(1) if counting manually or O(m) if splitting strings into arrays. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expecting an array traversal with string manipulation to count words.
- question_mark
Looking for edge case handling like single-word sentences and uniform spaces.
- question_mark
Evaluates familiarity with split, length, and iterative maximum updates.
常见陷阱
外企场景- error
Counting spaces incorrectly when multiple spaces exist, although constraints prevent this.
- error
Forgetting to add one to the space count to get the total words.
- error
Assuming empty sentences or trimming is needed, which violates the problem constraints.
进阶变体
外企场景- arrow_right_alt
Return the index of the sentence with the maximum words instead of the count.
- arrow_right_alt
Count words ignoring punctuation or non-letter characters in sentences.
- arrow_right_alt
Handle sentences with varying spacing and leading/trailing spaces.