forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
47 lines (35 loc) · 1.01 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/// Source : https://leetcode.com/problems/sort-characters-by-frequency/
/// Author : liuyubobobo
/// Time : 2017-01-17
#include <iostream>
using namespace std;
/// Using Counting Sort
/// Time Complexity: O(n)
/// Space Complexity: O(256)
class Solution {
public:
string frequencySort(string s) {
pair<int, char> freq[256];
for(int i = 0 ; i < 256 ; i ++){
freq[i].first = 0;
freq[i].second = i;
}
for(int i = 0 ; i < s.size() ; i ++)
freq[s[i]].first ++;
sort(freq, freq + 256, greater<pair<int, char>>());
int index = 0;
for(int i = 0 ; i < s.size() ; i ++){
while(!freq[index].first)
index ++;
s[i] = freq[index].second;
freq[index].first --;
}
return s;
}
};
int main() {
cout << Solution().frequencySort("tree") << endl;
cout << Solution().frequencySort("cccaaa") << endl;
cout << Solution().frequencySort("Aabb") << endl;
return 0;
}