Problem:
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
“tree”
Output:
“eert”
Explanation:
‘e’ appears twice while ‘r’ and ‘t’ both appear once.
So ‘e’ must appear before both ‘r’ and ‘t’. Therefore “eetr” is also a valid answer.
Example 2:
Input:
“cccaaa”
Output:
“cccaaa”
Explanation:
Both ‘c’ and ‘a’ appear three times, so “aaaccc” is also a valid answer.
Note that “cacaca” is incorrect, as the same characters must be together.
Example 3:
Input:
“Aabb”
Output:
“bbAa”
Explanation:
“bbaA” is also a valid answer, but “Aabb” is incorrect.
Note that ‘A’ and ‘a’ are treated as two different characters.
Idea:
Counting sort
Solution 1:
Sort the string based on element frequency
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua // Running time: 289 ms class Solution { public: string frequencySort(string& s) { array<int, 128> f{0}; for(char c:s) ++f[c]; sort(s.begin(), s.end(), [&f] (char a, char b) { return f[a] > f[b] || (f[a] == f[b] && a > b); }); return s; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua // Running time: 139 ms class Solution { public: string frequencySort(string& s) { map<char, int> f; for(char c:s) ++f[c]; sort(s.begin(), s.end(), [&f] (char a, char b) { return f[a] > f[b] || (f[a] == f[b] && a > b); }); return s; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua // Running time: 29 ms class Solution { public: string frequencySort(string& s) { array<int, 128> f{0}; for(char c:s) ++f[c]; sort(s.begin(), s.end(), [&f] (char a, char b) { return f[a] > f[b] || (f[a] == f[b] && a > b); }); return s; } }; |
Solution 2:
Counting sort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua // Running time: 12 ms class Solution { public: string frequencySort(const string& s) { vector<int> f(128, 0); for(char c:s) ++f[c]; vector<pair<int,char>> v; for (int i = 0; i < 128; ++i) { if (f[i] > 0) v.emplace_back(f[i], i); } sort(v.rbegin(), v.rend()); string ans; for(const auto& kv : v) { ans.append(kv.first, kv.second); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment