Skip to content

Commit 24aaa96

Browse files
authored
Create 0451-sort-characters-by-frequency.kt
1 parent 8e434dc commit 24aaa96

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
 (0)