Skip to content

Commit ce2d458

Browse files
authored
Create 767-reorganize-string.js
1 parent a08ce3c commit ce2d458

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

767-reorganize-string.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @param {string} S
3+
* @return {string}
4+
*/
5+
function reorganizeString(S) {
6+
const map = {}
7+
const cArr = S.split('')
8+
for(let c of cArr) {
9+
let count = (map[c] || 0 ) + 1
10+
// impossible to form a solution
11+
if(count > (S.length + 1) / 2 ) {
12+
return ''
13+
}
14+
map[c] = count
15+
}
16+
17+
const pq = []
18+
for(let c of Object.keys(map)) {
19+
pq.push([c, map[c]])
20+
}
21+
pq.sort((a, b) => b[1] - a[1])
22+
23+
// build the result
24+
let sb = ''
25+
while(pq.length > 0) {
26+
let first = pq.shift()
27+
if (sb.length === 0 || first[0] !== sb.charAt(sb.length - 1)) {
28+
sb += first[0]
29+
if (--first[1] > 0) {
30+
pq.push(first)
31+
}
32+
} else {
33+
let second = pq.shift()
34+
sb += second[0]
35+
if (--second[1] > 0) {
36+
pq.push(second)
37+
}
38+
pq.push(first)
39+
}
40+
pq.sort((a, b) => b[1] - a[1])
41+
}
42+
43+
return sb
44+
}

0 commit comments

Comments
 (0)