Leetcode 每日一题——767. 重构字符串

767. 重构字符串

给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
在这里插入图片描述
该题的算法是优先队列加贪心(优先队列的API真的记不住),下面是C++的代码:

class Solution {
public:
    string reorganizeString(string S) {
        if(S.length()<2) return S;
        string result="";
        vector<int> chMap(26,0);
        int sLen=S.length();
        int maxCount=0;
        for (char i : S)
        {
            chMap[i-'a']++;
            maxCount=max(maxCount,chMap[i-'a']);
        }
        if(maxCount>(sLen+1)/2) return "";
        auto cmp = [&] (const char& char1, const char& char2){return chMap[char1-'a']<chMap[char2-'a'];};
        priority_queue<char,vector<char>,decltype(cmp)> priQueue{cmp};
        for(char i='a';i<='z';i++)
        {
            if(chMap[i-'a']>0) priQueue.push(i);
        }
        
        while(priQueue.size()>1)
        {
            char char1=priQueue.top();
            priQueue.pop();
            char char2=priQueue.top();
            priQueue.pop();
            result+=char1;
            result+=char2;
            if(--chMap[char1-'a']>0) priQueue.push(char1);
            if(--chMap[char2-'a']>0) priQueue.push(char2);
        }
        if(priQueue.size()>0) result+=priQueue.top();
        return result;
    }
};

运行效果:
在这里插入图片描述
相同的思路Python代码如下:

class Solution:
    def reorganizeString(self, S: str) -> str:
        if len(S) < 2 : return S
        sLen=len(S)
        chaMap=collections.Counter(S)
        maxCount=max(chaMap.items(),key=lambda x:x[1])[1]
        if maxCount>(sLen+1)//2: return ""
        priQueue=[(-x[1],x[0]) for x in chaMap.items()]
        heapq.heapify(priQueue)
        result=[]
        while(len(priQueue)>1):
            _,char1=heapq.heappop(priQueue)
            _,char2=heapq.heappop(priQueue)
            result.extend([char1,char2])
            chaMap[char1]-=1
            chaMap[char2]-=1
            if chaMap[char1]>0: heapq.heappush(priQueue, (-chaMap[char1], char1))
            if chaMap[char2]>0: heapq.heappush(priQueue, (-chaMap[char2], char2))
        if len(priQueue)>0: result.append(priQueue[0][1])
        return "".join(result)

运行效果:
在这里插入图片描述

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/reorganize-string

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值