看了答案之后,我表示我考虑多了,写复杂了,但是还是贴出来吧:
the code in c++ primer :
#include <iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string preword, currword,repword;
int currCnt = 0, maxCnt =1;
while (cin >> currword)
{
if (currword == preword)
{
++currCnt;
}
else
{
if (currCnt > maxCnt)
{
maxCnt = currCnt;
repword =preword;
}
currCnt = 1;
}
preword = currword;
}
if (maxCnt != 1)
{
cout << repword << " " << maxCnt <<endl;
}
else
{
cout << "no repeated word." << endl;
}
}
#include <iostream> #include<vector> #include<string> using namespace std; struct note { int local; int re_num; }; int main() { vector<string> stc; string s; cout << "Please input the strings gapping with balck space and end with 'ctrl+A' "<<endl; while(cin >> s) stc.push_back(s); int j = 0 , num = 0, size = stc.size(); vector<note> ivec; for(size_t i = 0; i != size-1; ++i) { num = 1; j = i+1; while(j != size-1 && stc[i] == stc[j++]) { ++num; } if (num != 0) { note a = {i,num}; ivec.push_back(a); } } note re_max = ivec[0]; for (size_t i = 1; i < ivec.size(); ++i) { if (re_max.re_num < ivec[i].re_num) { re_max = ivec[i]; } } cout << "The word : " << stc[re_max.local] << " repeat " << re_max.re_num << " times" << endl; }