-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2182-construct-string-with-repeat-limit.py
More file actions
34 lines (27 loc) · 1017 Bytes
/
2182-construct-string-with-repeat-limit.py
File metadata and controls
34 lines (27 loc) · 1017 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# time complexity: O(nlogk)
# space complexity: O(k)
from heapq import heapify, heappop, heappush
from typing import Counter
class Solution:
def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
maxHeap = [(-ord(c), cnt) for c, cnt in Counter(s).items()]
heapify(maxHeap)
result = []
while maxHeap:
charNeg, count = heappop(maxHeap)
char = chr(-charNeg)
use = min(count, repeatLimit)
result.append(char * use)
if count > use and maxHeap:
nextCharNeg, nextCount = heappop(maxHeap)
result.append(chr(-nextCharNeg))
if nextCount > 1:
heappush(maxHeap, (nextCharNeg, nextCount - 1))
heappush(maxHeap, (charNeg, count - use))
return "".join(result)
s = "cczazcc"
repeatLimit = 3
print(Solution().repeatLimitedString(s, repeatLimit))
s = "aababab"
repeatLimit = 2
print(Solution().repeatLimitedString(s, repeatLimit))