Leetcode 2114. Maximum Number of Words Found in Sentences
You are given a list of strings sentences
where each sentence i
consists of words separated by spaces. Your task is to return the maximum number of words that appear in a single sentence.
A sentence is defined as a string of spaces-separated words. For example, the string "This is a sample sentence"
has 5 words: “This”, “is”, “a”, “sample”, “sentence”.
Example:
sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Note:
i
contains only lowercase English letters and spaces.i
is at least 1.sentences
list.Here’s a possible implementation in C++:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
int mostWordsFound(std::vector<std::string>& sentences) {
int maxWords = 0;
for(const std::string& sentence : sentences) {
// Using stringstream to split the sentence into words
std::stringstream ss(sentence);
std::string word;
int wordCount = 0;
while (ss >> word) {
wordCount++;
}
// Update the maximum words found if the current sentence has more words
maxWords = std::max(maxWords, wordCount);
}
return maxWords;
}
// Example usage:
int main() {
std::vector<std::string> sentences = {"alice and bob love leetcode", "i think so too", "this is great thanks very much"};
std::cout << "Maximum number of words in a single sentence: " << mostWordsFound(sentences) << std::endl;
return 0;
}
n
is the number of sentences and m
is the average length of a sentence, splitting each sentence into words runs in O(m) time.Thus, with efficient handling using string streams, the solution is optimized for typical sentence processing scenarios.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?