C++ 统计字符串中每个字符出现的次数,并按照字符出现的次数排序
此题为58同城的2018年研发实习生笔试题
#pragma warning(disable:4996)
#include <stdio.h>
#include<iostream>
#include<vector>
#include<string>
using namespace std;
using std::cout;
using std::cin;
using std::vector;
struct s {
int count;
char strl;
}s_str[128];
int main()
{
int cnt[128] = { 0 };
int pre[128];
string str;
cin >> str;
int len;
for (len= 0; str[len] != ‘\0’; len++)
cnt[str[len]]++;
int number=0;
bool flag = false;
for(int j=0;j<128;j++)
if (cnt[str[j]] != 0)
{
flag = false;
for (int i = 0; i < number; i++)
{
if (str[j] == s_str[i].strl)
{
flag = true;
break;
}
}
if (flag == false)
{
s_str[number].count = cnt[str[j]];
s_str[number].strl = str[j];
number++;
}
}
char temp;
int tempcount;
for(int i=0;i<number;i++)
for (int j = 0; j < number – i – 1; j++)
{
if (s_str[j + 1].count > s_str[j].count|| (s_str[j + 1].count == s_str[j].count&&s_str[j+1].strl>s_str[j].strl))
{
temp = s_str[j + 1].strl;
s_str[j + 1].strl = s_str[j].strl;
s_str[j].strl = temp;
tempcount = s_str[j + 1].count;
s_str[j + 1].count = s_str[j].count;
s_str[j].count = tempcount;
}
}
for (int j = 0; j < number; j++)
cout << s_str[j].strl << ” ” << s_str[j].count << endl;
system(“pause”);
return 0;
}