Python solution using collections.Counter.most_common and a "filling" method, beats 95%


  • 0
    T

    Here is the solution:

    def rearrangeString(self, str, k):
    
        if k == 0 or len(str) == len(set(str)):
            return str
    
        import collections
        
        l = len(str)
        w = l//k
        
        r = l % k
        if r == 0:
            r = k
        else:
            w += 1
        
        array = ["" for i in range(w)]
    
        table = collections.Counter(str).most_common()
        
        m = table[0][1]
    
        if m > w:
            return ""
        elif m == w:
            n = 1
            while n < len(table) and table[n][1] == m:
                n += 1
            if n > r:
                return ""
    
        x = 0
        y = 0
        for item in table:
            for i in range(item[1]):
                array[x] += item[0]
                if x == w-1 or (x == w-2 and y >= r):
                    x = 0
                    y += 1
                else:
                    x += 1
        
        return "".join(array)

Log in to reply
 

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