forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
40 lines (33 loc) · 1.01 KB
/
index.ts
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
// TODO: Refactor Me
export const frequencySort = (str: string) => {
const charactorFrequency = countCharactorFrequency(str)
const sortedFrequency = getSortedFrequency(charactorFrequency)
let res = []
for (let i = 0; i < sortedFrequency.length; i++) {
res.push(
...Array(charactorFrequency[sortedFrequency[i]]).fill(
String.fromCharCode(sortedFrequency[i]),
),
)
}
return res.join('')
}
const countCharactorFrequency = (str: string) => {
const charactorFrequency = Array(128).fill(0)
for (let i = 0; i < str.length; i++) {
charactorFrequency[str.charCodeAt(i)]++
}
return charactorFrequency
}
const getSortedFrequency = (charactorFrequency: number[]) => {
const sortedFrequency = [0]
for (let i = 1; i < charactorFrequency.length; i++) {
for (let j = 0; j < sortedFrequency.length; j++) {
if (charactorFrequency[i] >= charactorFrequency[sortedFrequency[j]]) {
sortedFrequency.splice(j, 0, i)
break
}
}
}
return sortedFrequency
}