题意: 给你一个非空的字符串 s 和一个整数 k, 你要将这个字符串中的字母进行重新排列,使得重排后的字符串中相同字母的位置间隔距离至少为 k。 所有输入的字符串都由小写字母组成,如果找不到距离至少为 k 的重排结果,请返回一个空字符串 ""。 数据范围: 题目没说. 解法: 类似leetcode 767: https://blog.csdn.net/weixin_44178736/article/details/114006786 依据对拼消耗思想: 可以看作每次取出一个数量最大的,然后选出另外k-1个对拼消耗, 如果存在无法被消耗掉的字符,那么就无解了. 消耗过程用大顶堆进行模拟. code: #define PI pair<int,char> class Solution { public: string rearrangeString(string s, int k) { if(!k){ sort(s.begin(),s.end()); return s; } // map<char,int>mp; int n=s.size(); //判断是否有解 int ma=0; for(int i=0;i<n;i++){ mp[s[i]]++; ma=max(ma,mp[s[i]]); } priority_queue<PI,vector<PI>, less<PI> >q; for(auto i:mp){ q.push({i.second,i.first}); } string ans; while(q.size()){ if(q.size()<k){ while(q.size()){ PI x=q.top();q.pop(); if(x.first>1)return "";//无解 ans+=x.second; } break; } stack<PI>s; for(int i=0;i<k;i++){ PI x=q.top();q.pop(); ans+=x.second; x.first--; if(x.first>0){ s.push(x); } } while(s.size()){ PI x=s.top();s.pop(); q.push(x); } } return ans; } };