Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告

1 解题思想

题目要求给一个字符串,要求将字符串中的字符,按照字符出现的频率进行排序,从大到小的输出(某个字符出现了多少就输出多少次,只是重组)

解题方法:
1、统计
2、使用TreeMap,将相同频率的字符存在一起,然后按照key=频率的方式放入TreeMap
3、遍历TreeMap输出

2 原题

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.

3 AC解

public class Solution {
    public String frequencySort(String s) {
        int frequency[] = new int[256];
        for(char c:s.toCharArray()){
            frequency[c] ++;
        }
        // 统计频率,使用Treemap排序,这里白板写的代码,直接将频率取反,这样方便
        TreeMap<Integer,String> map= new TreeMap<Integer,String>();
        for(int i=0;i<256;i++){
            if(frequency[i] == 0) continue;
            StringBuilder sb = new StringBuilder(map.getOrDefault(-frequency[i],""));
            for(int j=0;j<frequency[i];j++)
                sb.append((char)i);
            map.put(-frequency[i],sb.toString());
        }
        StringBuilder sb = new StringBuilder();
        Iterator it = map.keySet().iterator();
        while(it.hasNext()){
            Integer key = (Integer)it.next();
            sb.append(map.get(key));
        }
        return sb.toString();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值