#2114
Maximum Number of Words Found in Sentences
Easy String scanning
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Each sentence is words separated by single spaces. Return the largest word count among all sentences.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: which sentence has the most words?
Why this works: words are separated by exactly one space, so words = spaces + 1. Counting spaces avoids building arrays with split().
Example: ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
4 spaces → 5 words3 spaces → 4 words5 spaces → 6 words → answer 6
✦Hints open one at a time
Words = spaces + 1 when words are separated by exactly one space.
Counting spaces avoids creating arrays with split().
↗Approach
For each sentence count the spaces, add one, and keep the maximum. split(" ").length also works but allocates a new array for every sentence.
</>Solution (Java)
class Solution {
public int mostWordsFound(String[] sentences) {
int best = 0;
for (String s : sentences) {
int words = 1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') words++;
}
best = Math.max(best, words);
}
return best;
}
}
!Common mistake
Forgetting the +1 — three words have only two spaces.
Complexity
- Time: O(total characters).
- Space: O(1).
