Input: sentences =["alice and bob love leetcode","i think so too", _" this is great thanks very much"_]Output: 6Explanation:
- The first sentence,"alice and bob love leetcode", has 5 words in total.- The second sentence,"i think so too", has 4 words in total.- The third sentence,"this is great thanks very much", has 6 words in total.Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.
Input: sentences =["please wait", _" continue to fight"_, _" continue to win"_]Output: 3Explanation: It is possible that multiple sentences contain the same number of words.In this example, the second and third sentences(underlined) have the same number of words.
Each sentence is a string of words separated by spaces. The number of words in a sentence is the number of spaces plus one. We can split each sentence by spaces and count the words, then return the maximum count.
classSolution {
public:int mostWordsFound(vector<string>& sentences) {
int ans =0;
for (auto& s : sentences) {
int cnt =1;
for (char c : s) if (c ==' ') cnt++;
ans = max(ans, cnt);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcmostWordsFound(sentences []string) int {
ans:=0for_, s:=rangesentences {
cnt:=1fori:=0; i < len(s); i++ {
ifs[i] ==' ' {
cnt++ }
}
ifcnt > ans {
ans = cnt }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintmostWordsFound(String[] sentences) {
int ans = 0;
for (String s : sentences) {
int cnt = 1;
for (char c : s.toCharArray()) if (c ==' ') cnt++;
ans = Math.max(ans, cnt);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmostWordsFound(sentences: Array<String>): Int {
var ans = 0for (s in sentences) {
var cnt = 1for (c in s) if (c ==' ') cnt++ ans = maxOf(ans, cnt)
}
return ans
}
}
1
2
3
4
5
6
7
classSolution:
defmostWordsFound(self, sentences: list[str]) -> int:
ans =0for s in sentences:
cnt = s.count(' ') +1 ans = max(ans, cnt)
return ans