#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
map<string, int> mp;
map<string, int> ::iterator it;
bool is_alphanumerial(char c)
{
return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
}
int main()
{
string input, str;
getline(cin, input);
int len = input.length();
transform(input.begin(), input.end(), input.begin(), ::tolower);
int i = 0, s, e;
while (i < len)
{
while (!is_alphanumerial(input[i]) && i < len)
i++;
if (i == len)
break;
s = i;
while (is_alphanumerial(input[i]) && i < len)
i++;
e = i;
str = input.substr(s, e - s);
mp[str]++;
}
int max_cnt = 0;
string result;
for (it = mp.begin(); it != mp.end(); ++it)
{
if (it->second > max_cnt)
{
max_cnt = it->second;
result = it->first;
}
else if (it->second == max_cnt && it->first < result)
result = it->first;
}
cout << result << " " << max_cnt << endl;
return 0;
}
另一种更简单的思路:
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> mp;
map<string, int> ::iterator it;
int main()
{
char c;
string s;
while (c = getchar(), c != '\n')
{
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'z')
s.push_back(c);
else if (c >= 'A' && c <= 'Z')
s.push_back(c - 'A' + 'a');
else
{
if (!s.empty())
{
mp[s]++;
s.clear();
}
}
}
if (!s.empty())
{
mp[s]++;
s.clear();
}
int max_cnt = 0;
string result;
for (it = mp.begin(); it != mp.end(); ++it)
{
if (it->second > max_cnt)
{
max_cnt = it->second;
result = it->first;
}
else if (it->second == max_cnt && it->first < result)
result = it->first;
}
cout << result << " " << max_cnt << endl;
return 0;
}