用一个向量存下输入,占用空间,但是控制逻辑简单,理想解法是空间复杂度为o(1),在cin的时候完成整个控制逻辑;
#include<iostream>
using namespace std;
#include<vector>
int main()
{
vector<string> v;
string s;
while (cin >> s)
v.push_back(s);
s = v[0];
int count = 0;
for (auto rank = v.begin(); rank != v.end(); rank++)
{
if (*rank == s)
count++;
else
s = *rank, count = 1;
}
cout << "出现最多的单词是:" << endl << s << endl << "出现了" << count << "次";
return 0;
}