題目:編寫一個小程序,從標準輸入讀入一系列 string 對象,尋找連續重複出現的單詞。程序應該找出滿足以下條件的單詞的輸入位置:該單詞的後面緊跟着再次出現自己本身。跟蹤重複次數最多的單詞及其重複次數。輸出重複次數的最大值,若沒有單詞重複則輸出說明信息。例如,如果輸入是:
how, now now now brown cow cow
My code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
//vector<string> svec;
string preWord = "", word, maxWord;
int occurs = 0, maxOccurs = 0; //若有重複,記錄次數
while(cin >> word)
{
//第一次輸入,更新preWrod
if(preWord == "")
{
preWord = word;
occurs = 1;
continue;
}//如果出現重複單詞,記錄加1
if(preWord == word)
{
++occurs;
}//否則如果出現不同單詞則判斷,如果重複次數大於已記錄的最大值,則更新最大值
else
{
if(maxOccurs < occurs)
{
maxWord = preWord;
maxOccurs = occurs;
}
//更新preword,並從頭開始計數
preWord = word;
occurs = 1;
}
}
if(maxOccurs < occurs) //注意最後一次循環容易忽略
{
maxWord = word;
maxOccurs = occurs;
}
if(maxOccurs != 1 )
cout << maxWord << ": " << maxOccurs << endl;
else
cout << "There is no repetition!" << endl;
return 0;
}
reference answer;
#include<iostream>
#include<string>
using namespace std;
int main()
{
string preWord, currWord; //當前輸入的單詞及前一次單詞
string repWord; //重複次數最多的單詞
//當前單詞的重複次數及單詞重複的次數最大值
int currCnt = 0, maxCnt = 1;
cout << "Enter some words(Ctr+Z to end): "<< endl;
while(cin >> currWord)
{
if(currWord == preWord) //當前單詞重複出現
++currCnt;
else //出現新單詞
{
if(currCnt > maxCnt)//出現了重複次數更多的單詞,更新4
{
maxCnt = currCnt;
repWord = preWord;
}
currCnt = 1;
}
preWord = currWord;
}
if(currCnt > maxCnt)
{
maxCnt = currCnt;
repWord = preWord;
}
if(maxCnt != 1)
cout << '"' << repWord << '"' << " repeated for " << maxCnt << " times!" << endl;
else
cout << "There is no repeated word." << endl;
return 0;
}