- Sort Characters By Frequency
- 每天一道leetcode451-根据字符出现频率排序
- [451]Sort Character by Frequency
- [刷题防痴呆] 0451 - 根据字符出现频率排序 (Sort
- Leetcode 451. Sort Characters By
- 451. Sort Characters By Frequenc
- LeetCode - 451. Sort Characters
- 451. Sort Characters By Frequenc
- # LeetCode 451. Sort Characters
- LeetCode451. Sort Characters By
题目来源
将字符串中字符按频率排序。搞了半天,sort不会用,lambda表达式不会用…
class Solution {
public:
string frequencySort(string s) {
int n = s.size();
unordered_map<char, int> maps;
for (int i=0; i<n; i++)
maps[s[i]]++;
sort(s.begin(), s.end(), [&](char a, char b) {
return maps[a] > maps[b] || (maps[a] == maps[b] && a < b);
});
return s;
}
};
又看了看别的大神们的做法,直接先哈希一遍,然后搞一个buckets,存储出现频次为i的字符,然后再从大到小相加,得到结果,厉害,只要O(n)复杂度,不需要sort,代码如下:
class Solution {
public:
string frequencySort(string s) {
int n = s.size();
unordered_map<char, int> maps;
for (int i=0; i<n; i++)
maps[s[i]]++;
sort(s.begin(), s.end(), [&](char a, char b) {
return maps[a] > maps[b] || (maps[a] == maps[b] && a < b);
});
return s;
}
};
网友评论