In: Computer Science
// For an input string of words, find the most frequently
occurring word. In case of any ties, report any in output.
// Your algorithm should be of the runtime O(n) time where n is the
number of words in the string.
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
string findWord(vector<string>& tokens);
int main() {
string line = "FDo all the good you can, by all the
means you can,
in all the ways you can, in
all the places you can,
at all the times you can, to
all the people you can,
as long as ever you
can.";
// Convert string to a vector of words
char delimiter = ' ';
string token;
istringstream tokenStream(line);
vector<string> tokens;
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
cout << "The most frequently occuring word is: "
<< findWord(tokens) << endl;
}
string findWord(vector<string>& tokens) {
// Your code here
}
// Convert string to a vector of words
char delimiter = ' ';
string token;
istringstream tokenStream(line);
vector<string> tokens;
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
cout << "The most frequently occuring word is: "
<< findWord(tokens) << endl;
}
string findWord(vector<string>& tokens) {
// Your code here
}
";
// Convert string to a vector of words
char delimiter = ' ';
string token;
istringstream tokenStream(line);
vector<string> tokens;
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
cout << "The most frequently occuring word is: "
<< findWord(tokens) << endl;
}
string findWord(vector<string>& tokens) {
// Your code here
}
Here is the code for the above question :
#include <iostream>
#include <vector>
#include <sstream>
#include<unordered_map>
using namespace std;
string findWord(vector<string>& tokens);
int main() {
string line = "FDo all the good you can, by all the means you can, in all the ways you can, in all the places you can, at all the times you can, to all the people you can, as long as ever you can.";
// Convert string to a vector of words
char delimiter = ' ';
string token;
istringstream tokenStream(line);
vector<string> tokens;
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
cout << "The most frequently occuring word is: " << findWord(tokens) << endl;
}
string findWord(vector<string>& tokens) {
unordered_map <string, int> m;
//create a map of words, where each element is [word , frequency of the word]
for(int i = 0 ; i < tokens.size() ; i++){
if(m.count(tokens[i]) == 0){
m[tokens[i]] = 1;
}
else{
m[tokens[i]] ++;
}
}
//now iterate the map and find the word which has the maximum frequency
string freq = "";
int max = INT8_MIN;
for(auto x : m){
if(x.second > max){
freq = x.first;
max = x.second;
}
}
return freq;
}
Here is the ss and the output for your reference -
Please give a thumbs up if you like the answer. Thank you .