题解 | #字符统计#
字符统计
http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
#include<string>
#include<map>
using namespace std;
int main(){
string str;
while(cin>>str){
int count[124]={0};
int maxn=0;
for(int i=0;i<str.size();i++){
count[str[i]]++;
maxn=max(maxn,count[str[i]]);
}
while(maxn>0){
for(int i=0;i<124;i++){
if(count[i]==maxn){
cout<< (char)i;
}
}
maxn--;
}
}
return 0;
}
参考了前排大佬的思路: 1.建立字符到ASCII码的映射,然后定义超过ASCII码最大值的数组count[124],用下标i对应的元素表示i对应字符出现的次数,初始化为0. 2.读取并遍历字符串,当让字符a对应下标的元素count[a]++。 3.找出count中的最大值,即出现最多的次数。 4.从次数最大开始遍历字符串,若字符串对应count[a]等于当前次数,将其输出。然后次数减1继续遍历。直到次数为0跳出循环。