451. Sort Characters By Frequency

来源:互联网 发布:macbook下不了软件 编辑:程序博客网 时间:2024/06/06 21:05

Problem:

Given a string, sort it in decreasing order based on the frequency of characters.


solution:

#include<iostream>
#include<string>

using namespace std;

class Solution {
public:
string frequencySort(string s) {
int i, j, max, count;
string ns;
int org[256] = { 0 };
for (i = 0; i < s.length(); i++)
{
org[s[i]]++;
}
for (i = 0; i < 256; i++)
{
max = 0;
for (j = 0; j < 256; j++)
{
if (org[j] > max)
{
max = org[j];
count = j;
}
}
for (j = 0; j < max; j++)
{
ns += count;
}
org[count] = 0;
}
return ns;
}
};
int main()
{
string s;
cin >> s;
Solution solution;
cout << solution.frequencySort(s) << endl;
return 0;
}


原创粉丝点击