#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;
}
本文详细解读了一段C++代码,该代码用于从输入字符串中筛选并统计字母数字字符的出现频率。通过使用STL库中的map和transform函数,实现了字符过滤和频率统计的功能。此外,介绍了两种不同的实现思路,一种更为简洁,通过循环和条件判断直接进行字符处理和映射统计。
2009

被折叠的 条评论
为什么被折叠?



