Skip to content

Commit 02890bc

Browse files
authored
Update 767-reorganize-string.js
1 parent ce2d458 commit 02890bc

File tree

1 file changed

+29
-35
lines changed

1 file changed

+29
-35
lines changed

767-reorganize-string.js

Lines changed: 29 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,37 @@
22
* @param {string} S
33
* @return {string}
44
*/
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 ''
5+
const reorganizeString = function(S) {
6+
if (!S || S.length <= 1) {
7+
return S;
8+
}
9+
const freqs = Array(26).fill(0);
10+
const acode = 'a'.charCodeAt(0);
11+
for (let i = 0, n = S.length; i < n; i++) {
12+
const index = S.charCodeAt(i) - acode;
13+
freqs[index]++;
14+
if (freqs[index] > Math.ceil(n / 2)) {
15+
return '';
16+
}
17+
}
18+
const list = [];
19+
for (let i = 0, n = S.length; i < 26; i++) {
20+
if (freqs[i] === 0) {
21+
continue;
1322
}
14-
map[c] = count
23+
list.push({ch: String.fromCharCode(i + acode), freq: freqs[i]});
1524
}
16-
17-
const pq = []
18-
for(let c of Object.keys(map)) {
19-
pq.push([c, map[c]])
25+
list.sort((l1, l2) => l2.freq - l1.freq);
26+
const parts = [];
27+
for (let i = 0, n = list[0].freq; i < n; i++) {
28+
parts.push(list[0].ch);
2029
}
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)
30+
let idx = 0;
31+
for (let i = 1, n = list.length; i < n; i++) {
32+
for (let j = 0, m = list[i].freq; j < m; j++) {
33+
idx %= list[0].freq;
34+
parts[idx++] += list[i].ch;
3935
}
40-
pq.sort((a, b) => b[1] - a[1])
4136
}
42-
43-
return sb
44-
}
37+
return parts.join('');
38+
};

0 commit comments

Comments
 (0)