-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path451.sort-characters-by-frequency.java
80 lines (77 loc) · 1.73 KB
/
451.sort-characters-by-frequency.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.Arrays;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;
/*
* @lc app=leetcode id=451 lang=java
*
* [451] Sort Characters By Frequency
*/
// @lc code=start
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
class Solution {
public String frequencySort(String s) {
int[] count = new int[128];
CharacterIterator it = new StringCharacterIterator(s);
while (it.current() != CharacterIterator.DONE) {
++count[it.current()];
it.next();
}
for (int i = 0; i != 128; ++i) {
if (count[i] > 0) {
count[i] *= 128;
count[i] += i;
}
}
Arrays.sort(count);
StringBuilder s2 = new StringBuilder();
for (int i = 127; i >= 0; --i) {
var freq = count[i] >> 7;
var ch = (char) (count[i] & 127);
for (int j = 0; j < freq; ++j) {
s2.append(ch);
}
}
return s2.toString();
}
}
// @lc code=end
// class Solution
// {
// public:
// string frequencySort(string s)
// {
// vector<int> count(128);
// for (auto c : s)
// {
// ++count[c];
// }
// auto comp = [](const pair<char, int> &l, const pair<char, int> &r)
// {
// return l.second < r.second;
// };
// priority_queue<pair<char, int>,
// vector<pair<char, int>>, decltype(comp)>
// pq(comp);
// for (int i = 0; i != 128; ++i)
// {
// if (count[i] > 0)
// {
// pq.push({i, count[i]});
// }
// }
// auto pos = 0;
// while (!pq.empty())
// {
// auto &elem = pq.top();
// for (int i = 0; i != elem.second; ++i)
// {
// s[pos++] = elem.first;
// }
// pq.pop();
// }
// return s;
// }
// };