358_rearrange_string_k_distance_apart.py 文件源码

python
阅读 21 收藏 0 点赞 0 评论 0

项目:Machine_Learning_Playground 作者: yao23 项目源码 文件源码
def rearrangeString(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        if k == 0:
            return s
        h = [(-freq, ch) for (ch, freq) in collections.Counter(s).items()]
        heapq.heapify(h)
        res = []
        while len(res) < len(s):
            q = []
            for _ in xrange(k):
                if len(res) == len(s):
                    return ''.join(res)
                if not h:
                    return ''
                freq, ch = heapq.heappop(h)
                res.append(ch)
                if freq < -1:
                    q.append((freq+1, ch))
            while q:
                heapq.heappush(h, q.pop())
        return ''.join(res)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号