-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsortString.js
70 lines (58 loc) · 1.16 KB
/
sortString.js
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
const getMap = (s) => {
const chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
]
const counts = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0
]
for (let i = 0; i < s.length; i++) {
const charCode = s[i].charCodeAt(0)
counts[charCode - 97]++
}
for (let i = 0; i < counts.length; i++) {
if (counts[i] === 0) {
counts.splice(i, 1)
chars.splice(i, 1)
i--
}
}
return {
countMap: counts,
charMap: chars
}
}
const sortString = (s) => {
const { countMap, charMap } = getMap(s)
let result = ''
let dir = true
let i = 0
do {
result += charMap[i]
countMap[i]--
if (countMap[i] === 0) {
countMap.splice(i, 1)
charMap.splice(i, 1)
if (dir === true) {
i--
}
}
if (dir === true) {
i++
} else {
i--
}
if (i === charMap.length) {
dir = false
i--
} else if (i === -1) {
dir = true
i++
}
} while (countMap.length > 0)
return result
}
module.exports = sortString