-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsol.py
40 lines (30 loc) · 1.13 KB
/
sol.py
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
35
36
37
38
39
40
from heapq import heapify, heappop, heappush
from typing import Counter
class Solution:
def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
cnt = Counter(s)
items = list(zip([-ord(k) for k in cnt.keys()], cnt.values()))
heapify(items)
final = [None]
while items:
neg_asc_code, count = heappop(items)
c = chr(-neg_asc_code)
if c == final[-1]:
if not items:
break
sec_neg_asc_code, sec_count = heappop(items)
sec_c = chr(-sec_neg_asc_code)
final.append(sec_c)
heappush(items, (-ord(c), count))
if sec_count > 1:
heappush(items, (-ord(sec_c), sec_count - 1))
else:
add_size = min(repeatLimit, count)
final += [c] * add_size
if count - add_size > 0:
heappush(items, (-ord(c), count - add_size))
return "".join(final[1:])
s = Solution()
res = s.repeatLimitedString("cczazcc", 3)
# res = s.repeatLimitedString("aababab", 2)
print(res)