Question

// Your algorithm should be O(n) time where n is the number of words in the...

// Your algorithm should be 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 = "Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety two million miles is an utterly insignificant little blue green planet whose ape descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.";
  
   // 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


}


Homework Answers

Answer #1

//HERE IS THE CODE

// I HOPE I COULD HELP :)

//IF THERE ARE ANY CHANGES TO BE DONE PLEASE COMMENT, I WILL ANSWER

#include <iostream>

#include <vector>

#include <sstream>

#include<unordered_map>

using namespace std;

string findWord(vector<string>& tokens);

int main() {

   string line = "Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety two million miles is an utterly insignificant little blue green planet whose ape descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.";

   // 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

   unordered_map<string,int>freq;//map to store frequency of each word

   int max_freq=0;

   string max_freq_word="";

   for(int i=0;i<tokens.size();i++)

   {

       freq[tokens[i]]++;

       if(max_freq<freq[tokens[i]])

       {

           max_freq=freq[tokens[i]];

           max_freq_word=tokens[i];

       }

   }

   return max_freq_word;

}

OUTPUT

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT