0
点赞
收藏
分享

微信扫一扫

2114. 句子中的最多单词数


一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。

给你一个字符串数组 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 <= 100
1 <= sentences[i].length <= 100
sentences[i] 只包含小写英文字母和 ’ ’ 。
sentences[i] 的开头和结尾都没有空格。
sentences[i] 中所有单词由单个空格隔开。

== 单词数 = 空格数 + 1==
完整代码

class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int max=0;
int n=sentences.size();

for(int i=0;i<n;i++){
string str=sentences[i];
int len=str.size();
int count=0;
for(int j=0;j<len;j++){
if(str[j]==' ') count++;
}
if(max<count+1) max=count+1;
count=0;
str="";
}

return max;
}

};

官网题解:思想是一样的

class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int res = 0;
for (const string& sentence: sentences) {
// 单词数 = 空格数 + 1
int cnt = count(sentence.begin(), sentence.end(), ' ') + 1;
res = max(res, cnt);
}
return res;
}
};


举报

相关推荐

0 条评论