我想写一个类实现把字符串按出现次数重新排列,把次数多的放到前面,可是出现:
invalid use of member 'mp' in static member function
class Solution {
public:
unordered_map<char,int>mp;
static bool cmp(char a, char b){
return mp[a] > mp[b];
}
string frequencySort(string s) {
vector<char>num;
for(auto &ch:s){ //统计每个字符次数,并把出现过的字符放进num
if(mp.count(ch) == 0)
num.emplace_back(ch);
mp[ch]++;
}
sort(num.begin(),num.end(),cmp); //按字符出现次数排序
vector<string>ret( num.size() );
int i = 0;
for(auto &ch: num){
string s(mp[ch],ch);
ret[i] += s;
i++;
}
string ans;
for(auto &str:ret){
ans += str;
}
return ans;
}
};