LeetCode 451. Sort Characters By Frequency

Given a string, sort it in decreasing order based on the frequency of characters.
给定一个字符串,将字符串中按照字符出现的次数输出字符。

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.


方法:将字符串转化成字符数组,遍历数组,以字符作为键,出现的次数作为值,存在map中,然后桶排序,创建一个list桶,每个桶中也是一个list,存的是字符,然后倒序输出桶中的字符即可。

class Solution {
    public String frequencySort(String s) {
        Map<Character,Integer> map = new HashMap<>();
        for(char c : s.toCharArray()){
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }else{
                map.put(c,1);
            }
        }

        List<Character>[] bucket = new List[s.length()+1];
        for(char key :map.keySet() ){
            int fruency = map.get(key);
            if(bucket[fruency]==null){
                bucket[fruency] = new ArrayList();
            }
            bucket[fruency].add(key);

        }
        StringBuilder sb = new StringBuilder();
        for(int i=bucket.length-1;i>=0;i--){
            if(bucket[i]!=null){
                for(char c: bucket[i]){
                    for(int j=0;j<map.get(c);j++){
                        sb.append(c);
                    }
                }
            }
        }
        return sb.toString();


    }
}

猜你喜欢

转载自blog.csdn.net/weixin_36115316/article/details/79988647