767. Reorganize String

https://leetcode.com/problems/reorganize-string/

solution

  • 大顶堆,堆中的元素是(频率,字母)

class Solution:
    def reorganizeString(self, s: str) -> str:
        # 先最多,第二多,继续最多,第二多
        counter = collections.defaultdict(int)
        for char in s:
            counter[char] += 1

        heap = []
        for char, freq in counter.items():
            heapq.heappush(heap, [-freq, char])

        res = []
        while len(heap) > 1:
            f1, char1 = heapq.heappop(heap)
            f2, char2 = heapq.heappop(heap)
            if f1 < -1:
                heapq.heappush(heap, [f1+1, char1])
            if f2 < -1:
                heapq.heappush(heap, [f2+1, char2])
            res.append(char1)
            res.append(char2)
        if heap:
            if heap[0][0] < -1:
                return ""
            res.append(heapq.heappop(heap)[1])
        return "".join(res)

时间复杂度:O() 空间复杂度:O()

Last updated