Short python solution, beat 87% other solutions.


  • 2
    Y
    class Solution(object):
        def rearrangeString(self, str, k):
            if k == 0: return str
            counts = collections.Counter(str)
            heap = [[counts[key], key] for key in counts]
            res, j = ['']*len(str), 0
            while j < len(str):
                heap.sort(reverse=True)
                for i in range(k):
                    if i >= len(heap) or heap[i][0] == 0:
                        return ''.join(res) if j == len(str) else ''
                    res[j] = heap[i][1]
                    heap[i][0] -= 1
                    j += 1
            return ''.join(res)
    ``

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.