博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Sort Characters By Frequency
阅读量:5199 次
发布时间:2019-06-13

本文共 1678 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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.

题解:

类似. 利用Bucket Sort 按照频率把s的char放进bucket里, 再按照频率从大到小,重复频率次append到res中.

Time Complexity: O(n), n = s.length(). Space: O(n).

AC Java:

1 public class Solution { 2     public String frequencySort(String s) { 3         if(s == null || s.length() == 0){ 4             return s; 5         } 6          7         HashMap
freqMap = new HashMap
(); 8 for(char c : s.toCharArray()){ 9 freqMap.put(c, freqMap.getOrDefault(c, 0)+1);10 }11 12 StringBuilder [] bucket = new StringBuilder[s.length()+1];13 for(char c : freqMap.keySet()){14 int freq = freqMap.get(c);15 if(bucket[freq] == null){16 bucket[freq] = new StringBuilder();17 }18 for(int i = 0; i
=0; i--){25 if(bucket[i] != null){26 res.append(bucket[i]);27 }28 }29 return res.toString();30 }31 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6362027.html

你可能感兴趣的文章
Eclipse更新SDK速度慢,解决办法
查看>>
将博客搬至CSDN
查看>>
具体解释MVP矩阵之ViewMatrix
查看>>
Aizu 2170 Marked Ancestor(并查集变形)
查看>>
CDH安装
查看>>
【转载】Windows Server2012安装IIS服务器
查看>>
Global.asax 文件
查看>>
Ubuntu打开core dump
查看>>
crontab环境变量问题导致执行nodejs脚本失败
查看>>
Android : No Launcher activity found!
查看>>
Silverlight自定义控件开发:仪表盘
查看>>
三层交换机+VLAN中继
查看>>
分块的一些题(入门)
查看>>
xshell学习笔记
查看>>
记一次JavaWeb网站技术架构总结
查看>>
微服务架构实践之邮件通知系统改造
查看>>
sgu Ice-cream Tycoon
查看>>
EF CodeFirst,同项目多个数据库的迁移
查看>>
OLEDB的Excel的IMEX和HDR是什么意思
查看>>
《think in python》学习-10
查看>>