1. 题目
给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reorganize-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
参考 LeetCode 358. K 距离间隔重排字符串(贪心+优先队列),一模一样,K=2本题
struct cmp
{
bool operator()(pair<char,int>& a, pair<char,int>& b)
{
return a.second < b.second;//数量多的优先
}
};
class Solution {
public:
string reorganizeString(string S) {
int maxcount = 0;
vector<int> count(26, 0);
for(char c : S)
{
count[c-'a']++;
maxcount = max(maxcount, count[c-'a']);
}
if(maxcount > (S.size()+1)/2)
return "";
priority_queue<pair<char,int>, vector<pair<char,int>>, cmp> q;
for(int i = 0; i < 26; ++i)
{
if(count[i]>0)
q.push({
'a'+i, count[i]});
}
string ans;
while(q.size() >= 2)
{
vector<pair<char,int>> tmp;
int dis = 2;
while(dis--)
{
auto tp = q.top();
q.pop();
char c = tp.first;
int num = tp.second;
ans += c;
num--;
if(num > 0)
tmp.push_back({
c, num});
}
for(auto& p : tmp)
q.push(p);
}
while(!q.empty())
{
if(q.top().second == 1)
{
ans += q.top().first;
q.pop();
}
else
return "";
}
return ans;
}
};
4 ms 6.3 MB
本题还可以:
- 字符计数,按频数排序,大的先放
- 奇偶位置插空放置即可
class Solution {
public:
string reorganizeString(string S) {
int maxcount = 0;
vector<int> count(26, 0);
for(char c : S)
{
count[c-'a']++;
maxcount = max(maxcount, count[c-'a']);
}
if(maxcount > (S.size()+1)/2)
return "";
vector<pair<char,int>> char_num;
for(int i = 0; i < 26; i++)
{
if(count[i])
char_num.push_back({
'a'+i, count[i]});
}
sort(char_num.begin(), char_num.end(),[&](auto& a, auto& b){
return a.second > b.second;//数量多的优先
});
string ans(S.size(), ' ');
int idx = 0, i = 0;
while(i < S.size() && char_num[idx].second > 0)
{
ans[i] = char_num[idx].first;
i += 2;
if(--char_num[idx].second == 0)
idx++;
}
i = 1;
while(i < S.size() && char_num[idx].second > 0)
{
ans[i] = char_num[idx].first;
i += 2;
if(--char_num[idx].second == 0)
idx++;
}
return ans;
}
};
0 ms 6.2 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!