Skip to content

Commit 9af362a

Browse files
committed
Dec 17
1 parent 0ebd8c3 commit 9af362a

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from collections import Counter
2+
from heapq import heapify, heappop, heappush
3+
from typing import List, Optional, Tuple
4+
5+
6+
class Solution:
7+
def __heappop(self, heap: List[int]) -> Tuple[Optional[str], int]:
8+
if len(heap) == 0:
9+
return (None, 0)
10+
asc, count = heappop(heap)
11+
ch = chr(-asc)
12+
return (ch, count)
13+
14+
def __heappush(self, heap: List[int], ch: str, count: int):
15+
if count == 0:
16+
return
17+
entry = (-ord(ch), count)
18+
heappush(heap, entry)
19+
20+
def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
21+
freq = [(-ord(ch), count) for ch, count in Counter(s).items()]
22+
heapify(freq)
23+
string = ''
24+
while freq:
25+
curr_ch, curr_count = self.__heappop(freq)
26+
if string and string[-1] == curr_ch:
27+
next_ch, next_count = self.__heappop(freq)
28+
if next_ch is None and next_count == 0:
29+
break
30+
string += next_ch
31+
self.__heappush(freq, next_ch, next_count-1)
32+
self.__heappush(freq, curr_ch, curr_count)
33+
else:
34+
repeat = min(curr_count, repeatLimit)
35+
string += (curr_ch * repeat)
36+
self.__heappush(freq, curr_ch, curr_count-repeat)
37+
return string
38+
39+
40+
def main():
41+
s = 'cczazcc'
42+
repeatLimit = 3
43+
assert Solution().repeatLimitedString(s, repeatLimit) == 'zzcccac'
44+
45+
s = 'aababab'
46+
repeatLimit = 2
47+
assert Solution().repeatLimitedString(s, repeatLimit) == 'bbabaa'
48+
49+
50+
if __name__ == '__main__':
51+
main()

2024-12-December-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
| December 14 | [2762. Continuous Subarrays](https://leetcode.com/problems/continuous-subarrays/) | Medium | Unsolved |
2020
| December 15 | [1792. Maximum Average Pass Ratio](https://leetcode.com/problems/maximum-average-pass-ratio/) | Medium | Unsolved |
2121
| December 16 | [3264. Final Array State After K Multiplication Operations I](https://leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/) | Easy | Solved |
22-
| December 17 | []() | | |
22+
| December 17 | [2182. Construct String With Repeat Limit](https://leetcode.com/problems/construct-string-with-repeat-limit/) | Medium | Solved |
2323
| December 18 | []() | | |
2424
| December 19 | []() | | |
2525
| December 20 | []() | | |
@@ -39,5 +39,5 @@
3939
| Level | Problems | Solved | Unsolved |
4040
| --- | --- | --- | --- |
4141
| Easy | 4 | 4 | 0 |
42-
| Medium | 12 | 7 | 5 |
42+
| Medium | 13 | 8 | 5 |
4343
| Hard | 0 | 0 | 0 |

0 commit comments

Comments
 (0)