1. Description
给定一个字符串s,先按从小到大的顺序抽取字符添加到res字符串中,然后按从大到小的顺序抽取字符添加到res末尾,直到原字符串中所有字符抽取完毕。
2. Solution
关键在于先一遍扫描提取每个字符频数,然后向前向后添加,一有字符添加,就要及时将cnt减一。
3. Code
string sortString(string s, string res = "") { int cnt[26] = {}; for (auto ch: s) ++cnt[ch - 'a']; //读取每个字母频数 while (s.size() != res.size()) { //从小到大添加,从大到小添加 for (auto i = 0; i < 26; ++i) res += string(--cnt[i] >= 0 ? 1 : 0, 'a' + i); for (int i = 25; i >=0; --i) res += string(--cnt[i] >= 0 ? 1 : 0, 'a' + i); } return res; }