Skip to content

Commit 3fbc63e

Browse files
authored
Update 767-reorganize-string.js
1 parent 5340d72 commit 3fbc63e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

767-reorganize-string.js

+38
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,41 @@ const reorganizeString = function(S) {
3636
}
3737
return parts.join('');
3838
};
39+
40+
// another
41+
42+
/**
43+
* @param {string} s
44+
* @return {string}
45+
*/
46+
const reorganizeString = function(s) {
47+
const arr = Array(26).fill(0), a = 'a'.charCodeAt(0)
48+
for(let ch of s) arr[ch.charCodeAt(0) - a]++
49+
let max = 0, idx = -1
50+
for(let i = 0; i < 26; i++) {
51+
if(arr[i] > max) {
52+
max = arr[i]
53+
idx = i
54+
}
55+
}
56+
const n = s.length
57+
const res = Array(n)
58+
if(max > (n + 1) / 2) return ''
59+
60+
let i = 0
61+
while(arr[idx] > 0) {
62+
res[i] = String.fromCharCode(a + idx)
63+
i += 2
64+
arr[idx]--
65+
}
66+
67+
for(let j = 0; j < 26; j++) {
68+
while(arr[j]) {
69+
if(i >= n) i = 1
70+
res[i] = String.fromCharCode(a + j)
71+
i += 2
72+
arr[j]--
73+
}
74+
}
75+
return res.join('')
76+
};

0 commit comments

Comments
 (0)