File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ // Count and bucketsort by freq
2+ class Solution {
3+ fun frequencySort (s : String ): String {
4+ val counts = s
5+ .groupingBy { it }
6+ .eachCount()
7+
8+ val buckets = HashMap <Int , MutableList <Char >>()
9+ for ((char, count) in counts)
10+ buckets.getOrPut(count) { mutableListOf () }.apply { add(char) }
11+
12+ val res = StringBuilder ()
13+ for (count in s.length downTo 1 ) {
14+ buckets[count]?.forEach { char ->
15+ repeat (count) {
16+ res.append(char)
17+ }
18+ }
19+ }
20+
21+ return res.toString()
22+ }
23+ }
24+
25+ // Count and sort
26+ class Solution {
27+ fun frequencySort (s : String ): String {
28+ val counts = IntArray (128 )
29+
30+ for (c in s)
31+ counts[c.toInt()]++
32+
33+ val sortedCounts = counts
34+ .mapIndexed { i, v -> i to v }
35+ .filter { it.second > 0 }
36+ .sortedWith(compareBy({ - it.second },{ it.first }))
37+
38+ val res = StringBuilder ()
39+ for ((char, count) in sortedCounts) {
40+ repeat (count) {
41+ res.append(char.toChar())
42+ }
43+ }
44+
45+ return res.toString()
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments