Skip to content

Commit a8b67d4

Browse files
authored
Create 0767-reorganize-string.js
1 parent db64a15 commit a8b67d4

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

javascript/0767-reorganize-string.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* MaxHeap | Hashing
3+
* Time O(n*log(n)) | Space O(n)
4+
* https://leetcode.com/problems/reorganize-string/
5+
* @param {string} s
6+
* @return {string}
7+
*/
8+
var reorganizeString = function(s) {
9+
10+
const maxQ = new MaxPriorityQueue({
11+
compare: (a,b) => {
12+
return b[0] - a[0];
13+
}
14+
});
15+
16+
const freq = {};
17+
for(let i = 0; i < s.length; i++) {
18+
const char = s[i];
19+
freq[char] = (freq[char] && freq[char] + 1 || 1);
20+
}
21+
for(const key in freq) {
22+
const val = freq[key];
23+
maxQ.enqueue([val, key]);
24+
}
25+
26+
let orgStr = "";
27+
while(!maxQ.isEmpty()) {
28+
29+
const [occurance, char] = maxQ.dequeue();
30+
31+
if(orgStr[orgStr.length - 1] === char) {
32+
33+
if(maxQ.isEmpty()) return "";
34+
35+
const [occurance1, char1] = maxQ.dequeue();
36+
orgStr += char1;
37+
if(occurance1-1) {
38+
maxQ.enqueue([occurance1-1, char1]);
39+
}
40+
maxQ.enqueue([occurance, char]);
41+
} else {
42+
orgStr += char;
43+
if(occurance-1) {
44+
maxQ.enqueue([occurance-1, char]);
45+
}
46+
}
47+
}
48+
49+
return orgStr;
50+
};

0 commit comments

Comments
 (0)