767. Reorganize String

42 篇文章 0 订阅
16 篇文章 0 订阅

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].

思路:

最开始想分奇数位,偶数位填充,按照出现次数从高到低填充,优先选用剩余空间的填,有点贪心的味道

from collections import Counter
class Solution:
    def reorganizeString(self, S):
        """
        :type S: str
        :rtype: str
        """
        if len(S) == 1: return S
        p = ['']*len(S)
        d = Counter(S)
        i, j = 0, 1
        most = d.most_common(1)[0]
        
        try:
            while len(d):
                most = d.most_common(1)[0]
                if i<j:
                    for _ in range(most[1]):
                        p[i] = most[0]
                        i += 2
                else:
                    for _ in range(most[1]):
                        p[j] = most[0]
                        j += 2
                d.pop(most[0])
            return ''.join(p)
        except:
            return ''
但是WA,比如每个字母的count为4,4,2,最后会出现2填不进去的情况

错误的原因在于太贪了,每次都把所有的相同字母填进去,note that填进去一个自后,剩余的字母count就要重新计算了

所以就维持一个priority queue实时选取就好了,每次可以实时选取2个字母,也可以选取1个字母(这里以2个为例)

选取1个字母就要注意前后2次选取的字母不要重复

from collections import Counter
import heapq

class Solution:
    def reorganizeString(self, S):
        """
        :type S: str
        :rtype: str
        """
        ret = ''
        pq = []
        c = Counter(S)
        for k, v in c.items():
            heapq.heappush(pq, (-v, k))
        
        prev_key = ''
        while pq:
            v, k = heapq.heappop(pq)
            if k == prev_key:
                if not pq:  return ''
                vv, kk = heapq.heappop(pq)
                heapq.heappush(pq, (v,k))
                v, k = vv, kk
                
            ret += k
            if v+1<0:
                heapq.heappush(pq, (v+1, k))
            prev_key = k
            
        return ret

或者写得更简单点

from collections import Counter
import heapq

class Solution:
    def reorganizeString(self, S):
        """
        :type S: str
        :rtype: str
        """
        ret = ''
        pq = []
        c = Counter(S)
        for k, v in c.items():
            heapq.heappush(pq, (-v, k))
        
        # previous key value
        prev_v, prev_k = 0, ''
        while pq:
            v, k = heapq.heappop(pq)
            ret += k
            if prev_v<0:
                heapq.heappush(pq, (prev_v, prev_k)) # delay one loop to prevent aab
            prev_v, prev_k = v+1, k    # store current key value for latter enqueue
            
        return ret if len(ret)==len(S) else ''






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值