我是靠谱客的博主 昏睡寒风,最近开发中收集的这篇文章主要介绍Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告1 解题思想2 原题3 AC解,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
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();
}
}
最后
以上就是昏睡寒风为你收集整理的Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告1 解题思想2 原题3 AC解的全部内容,希望文章能够帮你解决Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告1 解题思想2 原题3 AC解所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复