LeetCode.451 Sort Characters By Frequency

来源:互联网 发布:dota改键位软件 编辑:程序博客网 时间:2024/05/22 03:49

题目:

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.
分析:

class Solution {    public String frequencySort(String s) {     //给定字符串包含大写,按各字母出现频率的降序返回结果        //思路:使用字母数组来存储出现的次数,最后使用List集合返回结果        List<Character>[]bucket=new List[s.length()];        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();        for(char c:s.toCharArray()){            hm.put(c,hm.getOrDefault(c,0)+1);        }        for(char c:hm.keySet()){            int fre=hm.get(c);            //以频率作为下标,            if(bucket[fre]==null){                bucket[fre]=new ArrayList<>();            }            //出现相同次数的距离添加在一个下标频率相同的区域            bucket[fre].add(c);        }        //将数据输出        StringBuffer sb=new StringBuffer();        List<Character> list=new ArrayList<>();        for(int i=bucket.length-1;i>=0;i--){            if(bucket[i]!=null){                //将集合中的数据存入String                for(Character c:bucket[i]){                    for(int times=0;times<i;times++){                        sb.append(c);                    }                }            }        }        return sb.toString();            }}

分析2(参考答案):

class Solution {    public String frequencySort(String s) {         //给定字符串包含大写,按各字母出现频率的降序返回结果        //思路:使用数组存储各字母,最后排序        int [] alpha =new int[256];        char [] chs=s.toCharArray();        char [] res=new char[chs.length];        for(char c:chs){            alpha[c]++;        }        //i作为已经存储的元素的下标,i的增加在后面的元素填充后更新        for(int i=0;i<res.length;){            int max=0;            int c=0;                        for(int j=0;j<alpha.length;j++){                //找出最大的元素                if(alpha[j]>max){                    max=alpha[j];                    c=j;                }            }                        //将最大值位置赋0,存入res            alpha[c]=0;                        while(max-->0){                //从当前位置开始填充元素                res[i++]=(char)c;            }           }        return new String(res);        }}