LeeCode 451. Sort Characters By Frequency

来源:互联网 发布:yy网络怎么创建直播间 编辑:程序博客网 时间:2024/06/05 00:28

原题

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.

解析

题目很清晰,把字符串里的字符按频率排序。
按频率排序首先得计算出频率来。先用map存下频率,由于只有256个字符,直接冒泡排序,得到结果。再把排序好的结果输出成字符串。
时间复杂度O(n),空间复杂度O(1)。

代码


string frequencySort(string s) {        pair<char,int> p_map[256];        for(int i = 0; i < 256; i++) {            p_map[i].first = i;            p_map[i].second = 0;        }        for(int i = 0; i < s.length(); i++) {            p_map[s[i]].second++;        }        pair<char,int> tem;        for(int i = 255; i > 0; i--) {            for(int j = 0; j < i; j++) {                if(p_map[j].second < p_map[j + 1].second) {                    tem = p_map[j];                    p_map[j] = p_map[j + 1];                    p_map[j + 1]=tem;                }            }        }        string res = "";        for(int i = 0; i < 256; i++) {            for(int j = 0; j < p_map[i].second; j++) {                res += p_map[i].first;            }        }        return res;    }




原创粉丝点击