Easy
题目描述
句子 是由单个空格分隔的单词列表,且不含前导或尾随空格。
给你一个字符串数组 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]中的所有单词由单个空格分隔
解题思路
解题思路
这是一道简单的字符串处理题目,核心在于统计每个句子中的单词数量,然后找出最大值。
方法分析
方法一:计算空格数量
- 观察发现,一个句子中单词数 = 空格数 + 1
- 这是因为 n 个单词之间有 n-1 个空格
- 遍历每个句子,统计空格字符的个数,加1即为单词数
方法二:字符串分割
- 使用语言内置的字符串分割函数
- 将句子按空格分割成单词数组,数组长度即为单词数
- 这种方法更直观,但可能有额外的空间开销
方法三:状态机遍历
- 逐字符遍历,使用标志位记录当前是否在单词内
- 遇到非空格字符且之前是空格时,单词数+1
- 这种方法空间复杂度最优
推荐解法:方法一 计算空格数量的方法最简洁高效,代码量少,时间和空间复杂度都很优秀。对于这道题目的数据规模,是最佳选择。
代码实现
class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int maxWords = 0;
for (const string& sentence : sentences) {
int spaceCount = 0;
for (char c : sentence) {
if (c == ' ') {
spaceCount++;
}
}
maxWords = max(maxWords, spaceCount + 1);
}
return maxWords;
}
};
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
max_words = 0
for sentence in sentences:
space_count = sentence.count(' ')
max_words = max(max_words, space_count + 1)
return max_words
public class Solution {
public int MostWordsFound(string[] sentences) {
int maxWords = 0;
foreach (string sentence in sentences) {
int spaceCount = 0;
foreach (char c in sentence) {
if (c == ' ') {
spaceCount++;
}
}
maxWords = Math.Max(maxWords, spaceCount + 1);
}
return maxWords;
}
}
/**
* @param {string[]} sentences
* @return {number}
*/
var mostWordsFound = function(sentences) {
let maxWords = 0;
for (let sentence of sentences) {
let wordCount = sentence.split(' ').length;
maxWords = Math.max(maxWords, wordCount);
}
return maxWords;
};
复杂度分析
| 复杂度类型 | 分析结果 |
|---|---|
| 时间复杂度 | O(n × m),其中 n 是句子数量,m 是句子的平均长度 |
| 空间复杂度 | O(1),只使用常数级别的额外空间 |