Leet code problem 2114
Difficulty: Easy —
Solution
This is pretty straight forward.
- You can just count the number of words
text.split(" ")
- Or count the spaces between letters because the question already mentioned that there will be no trailing/leading spaces and separated by a single space character
Implementation
Code from github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class L2114_MaxNumberOfWordsFoundInSentences {
/***
* Using Java builtin function split() to count words
* @param sentences
* @return
*/
public int mostWordsFound(String[] sentences) {
int maxCount = 0;
for(int i = 0; i < sentences.length; i++) {
int length = sentences[i].split(" ").length;
if (length > maxCount) {
maxCount = length;
}
}
return maxCount;
}
/***
* Faster by counting the spaces
* @param sentences
* @return
*/
public int mostWordsFound_2ndApproach(String[] sentences) {
if (sentences.length == 0) {
return 0;
}
int maxCount = 0;
for(int i = 0; i < sentences.length; i++) {
int length = countSpaces(sentences[i]);
if (length > maxCount) {
maxCount = length;
}
}
return ++maxCount;
}
private int countSpaces(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
}