题目描述
知识点
哈希
我的实现
码前思考
按照题目的定义,并不是仅仅以空格为分隔符分割单词的,其他只要不是数字或者字母的字符都可以作为分割符!!!
所以我们选择一个个字符的读取,只要读到一个非字母或者数字时,就代表生成了一个单词(前提是这个单词是非空的!)
代码实现
#include<stdio.h>
#include<map>
#include<string>
#include<iostream>
using namespace std;
bool isAOrN(char a){
if(a>='0' && a<='9' || a>='A' && a<='Z' || a>='a' && a<='z'){
return true;
}else{
return false;
}
}
int main(){
map<string,int> cnt;
string input;
//要输入整行的字符使用cin
getline(cin,input);
int idx=0;
string maxKey;
int maxNum=0;
while(idx < input.length()){
string word;
while(isAOrN(input[idx])){
if(input[idx] >='A' && input[idx] <= 'Z'){
word += (input[idx] - 'A' + 'a');
}else{
word += input[idx];
}
idx++;
}
if(!word.empty()){
if(cnt.find(word) != cnt.end()){
cnt[word]++;
}else{
cnt[word]=1;
}
if(cnt[word]>maxNum || cnt[word] == maxNum && word<maxKey){
maxKey = word;
maxNum = cnt[word];
}
}
idx++;
}
cout<<maxKey<<" "<<maxNum;
return 0;
}
码后反思
这里使用的是自己写的函数判断字符和转换字符,其实也可以用库里的函数:toupper()、tolower()、isalnum()
;