題目: LeetCode - 451. Sort Characters By Frequency
題目說明
給一個 String,將 String 裡面的字元按照個數排序,例如: tree
-> eert
or eetr
。需要注意的是大小寫為不同的字元。
解題思路
先使用 hash_map 得到每個字出現的次數,再用 Vector 排序,最後串接到 String 即可。
參考解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| static auto __ = []() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }(); class Solution { public: static bool cmp(const pair<char, int>& l,const pair<char, int>& r) { return l.second > r.second; } string frequencySort(string s) { int length = s.size(); string res; res.reserve(length); unordered_map<char, int> hash; for(auto c : s) ++hash[c]; vector<pair<char, int>> v(hash.begin(), hash.end()); sort(v.begin(), v.end(), cmp); for(auto i : v) res.append(i.second, i.first); return res; } };
|