Leetcode 767 Reorganize String
题目原文
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]
.
题意分析
重构序列,使得任意两个相邻字符不相同。如果不可以返回“”。
解法分析
本题关键是从原string得到一个map,用以记录每个字符出现的次数,将出现次数最多的一个或多个元素作为框架,在间隙中一次填入其他元素。为了给字符出现次数排序,且对应处相应字符,本代码中建立了一个元素为pair的vector,first为字符,second为出现次数。structure为出现次数最多的元素组成的string,将除开出现次数最多的元素外所有元素按出现次数依次排成一个串,如b3c2f1,排成一串为bcfbcb,如a4,则需要在a的三个间隙中依次加入上述串,等同于将a插入上述串中abcfabcba。C++代码如下:
class Solution {
public:
static bool myCompare(pair<char,int> a,pair<char,int> b){
return a.second>b.second;
}
string reorganizeString(string S) {
unordered_map<char,int> count;
int maxCount=0;
int sum=0;
for(auto s:S){
count[s]++;
}
vector<pair<char,int>> charCount;
for(auto iter=count.begin();iter!=count.end();iter++){
charCount.push_back((*iter));
}
sort(charCount.begin(),charCount.end(),myCompare);
for(auto ss:charCount){
sum+=ss.second;
}
maxCount=charCount[0].second;
if((sum-maxCount)<(maxCount-1))
return "";
int i;
string res;
int theSame=0;
string structure;
for(i=0;i<charCount.size();i++){
if(charCount[i].second==charCount[0].second){
theSame++;
structure.push_back(charCount[i].first);
}
else
break;
}
for(i=theSame;i<=(int)charCount.size()-1;i++){//.size() is unsigned
res.push_back(charCount[i].first);
charCount[i].second--;
if(charCount[i].second==0){
charCount.erase(charCount.begin()+i);
i--;
if(i==charCount.size()-1){
i=theSame-1;
}
}
if(i==charCount.size()-1){
i=theSame-1;
}
}
cout<<res<<endl;
if(maxCount==1)
return S;
int internal=res.size()/(maxCount-1);
int rest=res.size()%(maxCount-1);
int start=0;
string finalRes;
for(i=1;i<=maxCount-1;i++){
finalRes+=structure;
finalRes+=res.substr(start,internal);
start=start+internal;
}
finalRes+=res.substr(start,rest);
finalRes+=structure;
//cout<<res<<endl;
return finalRes;
}
};