Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit24aaa96

Browse files
authored
Create 0451-sort-characters-by-frequency.kt
1 parent8e434dc commit24aaa96

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+
classSolution {
3+
funfrequencySort(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 (countin s.length downTo1) {
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+
classSolution {
27+
funfrequencySort(s:String):String {
28+
val counts=IntArray (128)
29+
30+
for (cin 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)

[8]ページ先頭

©2009-2025 Movatter.jp