1071 Speech Patterns

输出出现最多的那个字符串(字母和数字的组合),不区分大小写。
因为输入中可能有空格,因此用getline(cin, s);输入。
空字符串的个数不应该被统计,因此t长度不为0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cctype>
#include <map>
using namespace std;

int main() {
string s, t;
map<string, int> m;
getline(cin, s);
for (int i = 0; i < s.length(); i++) {
if (isalnum(s[i])) {
s[i] = tolower(s[i]);
t += s[i];
}
if (!isalnum(s[i]) || i == s.length() - 1) {
if (t.length() != 0) m[t]++;
t = "";
}
}
int resultMax = 0;
string resultStr = "";
for (auto it = m.begin(); it != m.end(); it++) {
if (it->second > resultMax) {
resultMax = it->second;
resultStr = it->first;
}
}
cout << resultStr << " " << resultMax << endl;

return 0;
}