Skip to content

Commit 36eb7e7

Browse files
authored
Create 767-Reorganize-String.py
1 parent a654750 commit 36eb7e7

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

767-Reorganize-String.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def reorganizeString(self, s: str) -> str:
3+
count = Counter(s) # Hashmap, count each char
4+
maxHeap = [[-cnt, char] for char, cnt in count.items()]
5+
heapq.heapify(maxHeap) # O(n)
6+
7+
prev = None
8+
res = ""
9+
while maxHeap or prev:
10+
if prev and not maxHeap:
11+
return ""
12+
# most frequent, except prev
13+
cnt, char = heapq.heappop(maxHeap)
14+
res += char
15+
cnt += 1
16+
17+
if prev:
18+
heapq.heappush(maxHeap, prev)
19+
prev = None
20+
if cnt != 0:
21+
prev = [cnt, char]
22+
return res

0 commit comments

Comments
 (0)