Skip to content

Commit 0206441

Browse files
committed
Add solution #767
1 parent deac60d commit 0206441

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -581,6 +581,7 @@
581581
764|[Largest Plus Sign](./0764-largest-plus-sign.js)|Medium|
582582
765|[Couples Holding Hands](./0765-couples-holding-hands.js)|Hard|
583583
766|[Toeplitz Matrix](./0766-toeplitz-matrix.js)|Easy|
584+
767|[Reorganize String](./0767-reorganize-string.js)|Medium|
584585
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
585586
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
586587
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|

solutions/0767-reorganize-string.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 767. Reorganize String
3+
* https://leetcode.com/problems/reorganize-string/
4+
* Difficulty: Medium
5+
*
6+
* Given a string s, rearrange the characters of s so that any two adjacent characters are
7+
* not the same.
8+
*
9+
* Return any possible rearrangement of s or return "" if not possible.
10+
*/
11+
12+
/**
13+
* @param {string} s
14+
* @return {string}
15+
*/
16+
var reorganizeString = function(s) {
17+
const charCount = new Map();
18+
for (const char of s) {
19+
charCount.set(char, (charCount.get(char) || 0) + 1);
20+
}
21+
22+
const maxHeap = [...charCount.entries()]
23+
.sort((a, b) => b[1] - a[1]);
24+
25+
if (maxHeap[0][1] > Math.ceil(s.length / 2)) {
26+
return '';
27+
}
28+
29+
const result = [];
30+
let index = 0;
31+
32+
while (maxHeap.length) {
33+
const [char, count] = maxHeap.shift();
34+
for (let i = 0; i < count; i++) {
35+
result[index] = char;
36+
index += 2;
37+
if (index >= s.length) index = 1;
38+
}
39+
}
40+
41+
return result.join('');
42+
};

0 commit comments

Comments
 (0)