Участник:Turk0v/Reorganize String

Материал из DISCOPAL
Перейти к: навигация, поиск
class Solution:
    def reorganizeString(self, S: str) -> str:
        import heapq
        my_heap = [(-S.count(c), c) for c in set(S)]
        heapq.heapify(my_heap)
        res_tmp = sum([-1*counter for counter, _ in my_heap])
        if res_tmp + my_heap[0][0] < -my_heap[0][0]-1:
            return ''
        res = list()
        while len(my_heap) >= 2:
            counter1, a1 = heapq.heappop(my_heap)
            counter2, a2 = heapq.heappop(my_heap)
            res.extend([a1, a2])
            if counter1 + 1:
                heapq.heappush(my_heap, (counter1+1, a1))
            if counter2 + 1:
                heapq.heappush(my_heap, (counter2+1, a2))
        return ''.join(res) + (my_heap[0][1] if my_heap else '')