題目描述
給定一個字符串,請將字符串裏的字符按照出現的頻率降序排列。
示例 1:
輸入:
“tree”
輸出:
“eert”
解釋:
'e’出現兩次,'r’和’t’都只出現一次。
因此’e’必須出現在’r’和’t’之前。此外,"eetr"也是一個有效的答案。
示例 2:
輸入:
“cccaaa”
輸出:
“cccaaa”
解釋:
'c’和’a’都出現三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正確的,因爲相同的字母必須放在一起。
示例 3:
輸入:
“Aabb”
輸出:
“bbAa”
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sort-characters-by-frequency
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
題解1-桶排序
import java.util.*;
class Solution
{
public String frequencySort(String str) {
HashMap hashMap = new HashMap(); //存放每個字符出現的次數
for (int i=0;i<str.length();i++)
{
if(hashMap.get(str.charAt(i))==null)
hashMap.put(str.charAt(i),1);
else
{
int number = (int)hashMap.get(str.charAt(i));
hashMap.put(str.charAt(i),number+1);
}
}
ArrayList[] arrayLists = new ArrayList[str.length()+1]; //桶,按照字符出現次數放到對應的桶中
Object[] objects = hashMap.keySet().toArray(); //得到所有元素
for(int i=0;i<objects.length;i++)//把元素放到對應的桶中
{
int num = (int)hashMap.get(objects[i]);
if(arrayLists[num]==null)
{
arrayLists[num] = new ArrayList();
}
arrayLists[num].add(objects[i]);
}
StringBuilder res = new StringBuilder();
for(int i=str.length();i>=0;i--) //遍歷桶
{
ArrayList list = arrayLists[i];
if(list!=null)
for (int k=0;k<list.size();k++)
{
for(int j=0;j<i;j++)
{
res.append(list.get(k));
//res = res+list.get(k);
}
}
}
return res.toString();
}
}
堆
import java.util.*;
class Node
{
char sss;
int num;
}
class Solution
{
public String frequencySort(String str)
{
if(str.length()<=1)
return str;
HashMap hashMap = new HashMap(); //存放每個字符出現的次數
for (int i=0;i<str.length();i++)
{
if(hashMap.get(str.charAt(i))==null)
hashMap.put(str.charAt(i),1);
else
{
int number = (int)hashMap.get(str.charAt(i));
hashMap.put(str.charAt(i),number+1);
}
}
PriorityQueue<Node> priorityQueue = new PriorityQueue(hashMap.size(),new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o2.num-o1.num;
}
});
Object[] objects= hashMap.keySet().toArray();
for (int i=0;i<objects.length;i++)
{
Node node = new Node();
node.num = (int)hashMap.get(objects[i]);
node.sss = (char)objects[i];
priorityQueue.add(node);
}
String res = "";
//System.out.println(priorityQueue.size());
int size = priorityQueue.size();
for(int i=0;i<size;i++)
{
Node myNode = priorityQueue.poll();
for(int j=0;j<myNode.num;j++)
{
res = res+myNode.sss;
}
//priorityQueue.poll();
}
//System.out.println(res);
return res;
}
}