2. Problem-solving ideas
- Intuitive idea is: orderly map <char, int> record number of letters and letter appears
- In the manner described in the title, the first order traversal map, map a reverse order traversal, the number of times until all the letters in the map until the occurrence 0
3. Algorithms
- Traversal string s, ordered by the map <char, int> the number of recording letters and letters appear
- Setting a flag indicating the current forward is a forward traverse the map, or reverse traversal map
- Traverse the map, if the number of occurrences of the letter X is not 0, then the result added to the letter string, the number of occurrences of the letter and a minus; otherwise, the number of occurrences of the letter X is 0, indicates that the letter has been It has been traversed, and have been added to the result string
- If, after a complete traversal of a map, all occurrences of the letters are 0, represents the entire string has been traversed over, then you can exit the loop and return the resulting string (PS: Actually exit condition may be: when the result of character the length of the original string and a string of the same length, may exit the loop)
4. Implement
class Solution {
public:
string sortString(string s) {
map<char, int> table;
for(auto c : s){
table[c] = table[c] + 1;
}
string res;
bool forward = 1;
while(table.size() != 0){
bool finish = true;
if(forward){
map<char, int>::iterator begin = table.begin();
map<char, int>::iterator end = table.end();
forward = 0;
for(; begin != end; begin++){
if(begin->second == 0){
continue;
}
finish = false;
res += begin->first;
begin->second = begin->second - 1;
}
}else{
map<char, int>::reverse_iterator begin = table.rbegin();
map<char, int>::reverse_iterator end = table.rend();
forward = 1;
for(; begin != end; begin++){
if(begin->second == 0){
continue;
}
finish = false;
res += begin->first;
begin->second = begin->second - 1;
}
}
if(finish)
break;
//if(res.size() == s.size()) //另一种退出条件
// break;
}
return res;
}
};
//巧妙解法
//该解法有个限制条件:s中出现的字符排序规则必须跟map对这些字符的排序规则保持一致
class Solution {
public:
string sortString(string s) {
string ans;
map<char,int > cnt;
for(auto item:s)cnt[item]++;
while(1){
for(char ch='a';ch<='z';++ch)
if(cnt[ch]!=0)cnt[ch]--,ans.push_back(ch);
for(char ch='z';ch>='a';--ch)
if(cnt[ch]!=0)cnt[ch]--,ans.push_back(ch);
if(ans.size()==s.size())break;
}
return ans;
}
};