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();
}
}