PAT-A1071, 题目地址:https://www.patest.cn/contests/pat-a-practise/1071
这道题比较基础,步骤大致如下:
- 将字符串全部统一大小写,并将所有non-alphanumerical字符变成空格以方便处理
- 利用字符串分割函数strtok以空格为分界面将字符串进行分割。
- 利用map数据结构对字符串进行存储,key是字符串,value是字符串出现的次数
- 遍历map,找出其中出现次数最多且最小的字符串
代码如下:
#include <string>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
using namespace std;
int main(){
char str[1048577];
char *p;
cin.getline(str, 1048577);
int length = strlen(str);
for(int i = 0; i < length; i++){
if(str[i] >= 'A' && str[i] <= 'Z'){ //统一大小写
str[i] += 'a' - 'A';
}
else if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= '0' && str[i] <= '9'));
else{
str[i] = ' '; //将其他non-alphanumerical字符都变成空格
}
}
map<string, int> m;
queue<string> q;
p = strtok(str, " ");
while(p != NULL){
q.push(string(p)); //字符串进行分割并存进queue
p = strtok(NULL, " ");
}
while(!q.empty()){
string str = q.front();
map<string, int>::iterator it = m.find(str);
q.pop();
if(it == m.end()){
m[str]= 1; //不存在则插入,并赋值为1
}
else{
it->second++;
}
}
int max = 0;
string res = "";
for(map<string, int>::iterator iter = m.begin(); iter != m.end(); iter++){
if(iter->second > max || (iter->second == max && iter->first < res)){
res = iter->first;
max = iter->second;
}
}
cout << res << " " << max << endl;
}