题目:
一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。
给你一个字符串数组 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 个单词。
思路:直接采用暴力遍历,我们发现最多的单词数目就是所在词块空格数目+1;
语法知识:
- vector arr(n) 定义一个动态数组,注意这里是用()而不是[ ]
- int max = *max_element(arr.begin(),arr.end()) 这是一个取数组里最大元素的函数
代码:
class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int n = sentences.size();
vector<int> arr(n);
for(int i=0;i<sentences.size();i++)
{
int count=0;
for(int j=0;j<sentences[i].length();j++)
{
if(sentences[i][j]==' ')
{
count++;
}
}
arr[i] = count;//储存到数组中
}
int max = *max_element(arr.begin(),arr.end());
return max+1;;
}
};