- Write a program to read strings from standard input looking for duplicated words.
- The program should find places in the input where one word is followed immediately by itself.
- Keep track of the largest number of times a single repetition occurs and which word is repeated.
- Print the maximum number of duplicates, or else print a message saying that no word was repeated.
For example, if the input is
- how now now now brown cow cow
the output should indicate that the word now occurred three times.
#include <iostream>
#include <string>
int main()
{
using std::cin; using std::cout; using std::endl;
using std::string;
// running median
string most_duplicated_str;
int most_duplicated_count = 0;
// loop variables
string prev_str;
string new_str;
int new_duplicate_count = 1;
while(cin >> new_str)
{
if (new_str != prev_str)
{
// check and update median
if (new_duplicate_count > most_duplicated_count)
{
most_duplicated_str = prev_str;
most_duplicated_count = new_duplicate_count;
}
// update prev_str
new_duplicate_count = 1;
prev_str = new_str;
continue;
}
++new_duplicate_count;
prev_str = new_str;
}
// check and update median for last word
if (new_duplicate_count > most_duplicated_count)
{
most_duplicated_str = prev_str;
most_duplicated_count = new_duplicate_count;
}
// print result
if(most_duplicated_count == 0)
cout << "# No Duplicated Words #\n";
else
cout << "Most duplicated word: " << most_duplicated_str << ", " << most_duplicated_count << " times.\n";
}
blue blue red red red blue green blue
theblue
should be output as the word with most occurences (4) or thered
as the word with most occurences in a row (3). \$\endgroup\$