Leetcode 767. Refactored strings
Question stem
Given a string S, check whether the letters can be rearranged so that two adjacent characters are different.
If feasible, output any feasible results. If not feasible, return an empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
Note:
S only contains lowercase letters and the length is in the interval [1, 500].
answer
Count the number of occurrences of letters, sort them in descending order according to the number of times, and then put the letters back to S in the order of odd first (index=0) and then even
class Solution {
public:
string reorganizeString(string S) {
int n = S.length();
int head = 0,tail = n-1;
vector<string> alphaCount(26,"");
if(n==0){
return "";
}else if(n==1){
return S;
}
for(int i = 0 ; i < n ; ++i){
alphaCount[S[i] - 'a'].push_back(S[i]);
}
//字符串长度即字符出现次数,按照字符出现次数降序排列
sort(alphaCount.begin(),alphaCount.end(),[&](string a,string b){
return a.length() > b.length();
});
if(alphaCount[0].length() > (n + 1) / 2){
return "";
}
//按照奇偶填充
int ptr = 0;
int evenPtr = 1;
int oddPtr = 0;
for(int i = 0;i<26;++i){
while(!alphaCount[i].empty() && oddPtr < n){
S[oddPtr] = alphaCount[i].back();
alphaCount[i].pop_back();
oddPtr += 2;
}
while(!alphaCount[i].empty()){
S[evenPtr] = alphaCount[i].back();
alphaCount[i].pop_back();
evenPtr += 2;
}
}
return S;
}
};