|
| 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() |
0 commit comments