LeetCode 767. Reorganize String Python字符串

231 篇文章 0 订阅
120 篇文章 1 订阅

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result.  If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].

-----------------------------

这题目看起来简单但是有些恶心,没有办法特别简单的code,简单来说有三种思路:

思路一:先摊平了,再利用Python字符串操作交叉

from collections import Counter

class Solution:
    def reorganizeString(self, S: str) -> str:
        l = len(S)
        ca = Counter(S)
        tmp, res = [], [None for i in range(l)]
        sorted_list = sorted([(v, k) for k, v in ca.items()])

        if (sorted_list[-1][0] > (l+1)>>1):
            return ""

        for cnt, ch in sorted_list:
            tmp.extend([ch for i in range(cnt)])

        half = l >> 1
        res[::2], res[1::2] = tmp[half:], tmp[:half]  # python大法好
        return "".join(res)

思路二:每次摆出现频率最高的两个,当然就用到了堆

class Solution(object):
    def reorganizeString(self, S):
        pq = [(-S.count(x), x) for x in set(S)]
        heapq.heapify(pq)
        if any(-nc > (len(S) + 1) / 2 for nc, x in pq):
            return ""

        ans = []
        while len(pq) >= 2:
            nct1, ch1 = heapq.heappop(pq)
            nct2, ch2 = heapq.heappop(pq)
            #This code turns out to be superfluous, but explains what is happening
            #if not ans or ch1 != ans[-1]:
            #    ans.extend([ch1, ch2])
            #else:
            #    ans.extend([ch2, ch1])
            ans.extend([ch1, ch2])
            if nct1 + 1: heapq.heappush(pq, (nct1 + 1, ch1))
            if nct2 + 1: heapq.heappush(pq, (nct2 + 1, ch2))

        return "".join(ans) + (pq[0][1] if pq else '')

思路三:每个都当成桶,但是code也不简洁

class Solution:
    def reorganizeString(self, S: str) -> str:
        if len(S) < 2:
            return S
        chars = Counter(S)
        highest = max(chars.values())
        freq_char_dict = defaultdict(list)
        for k, v in chars.items():
            freq_char_dict[v].append(k)
        out = [None for _ in range(len(S))]
        i = 0
        while highest > 0:
            ch = freq_char_dict.get(highest, [])
            if not ch:
                highest -= 1
                continue
            for c in ch:
                for _ in range(highest):
                    out[i] = c
                    i += 2
                    if i >= len(S):
                        i = 1
            highest -= 1
        out = "".join(out)
        for i in range(1, len(out)):
            if out[i] == out[i-1]:
                return ""
        return out

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值