2. 按照字符出现次数对字符串排序
451. Sort Characters By Frequency (Medium)
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.
实现思路:
- 1.建立map字典,统计字符串中每个元素出现的次数
- 2.建立集合数组,以map中的值为集合数组下表,map的键为集合数组元素
- 3.将集合数组从大到小赋值给新集合。因为可能r数组中的某些值为null,故要进行该操作
字符串方法简介
/**
* 用StringBuilder,StringBuffer,List 三种方法存储字符
* string创建的字符串,创建后不能改变
* StringBuilder,StringBuffer创建的字符串可以改变,
* 改变后最终可以用toString()方法转换为不变的字符串,
*
* 采用官方提供的方法:append()、insert()、reverse()、setCharAt()、setLength()
* 区别:StringBuilder线程不安全,执行速度块
* StringBuffer 线程安全,执行速度慢
*/
项目源码
package order;
/**
* @Author Janson
* @Date 2022/2/12 12:29
* @Version 1.0
*/
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* 2. 按照字符出现次数对字符串排序
* 451. Sort Characters By Frequency (Medium)
*
* 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.
*/
public class Order3_frequencySort {
public static void main(String[] args) {
String str = "tree";
char[] ch = str.toCharArray();
//1.建立map字典,统计字符串中每个元素出现的次数
Map<Character, Integer> frequencyForNum = new HashMap();
for (char c: ch){
//关键一步,主要功能就是统计字符串中出现相同字符的数目
frequencyForNum.put(c,frequencyForNum.getOrDefault(c,0)+1);
}
//2.建立集合数组,以map中的值为集合数组下表,map的键为集合数组元素
List<Character>[] frequencyBucket = new ArrayList[ch.length+1];
for (char c: frequencyForNum.keySet()) {
int f = frequencyForNum.get(c);
if (frequencyBucket[f]==null){
frequencyBucket[f] = new ArrayList<>();
}
frequencyBucket[f].add(c);
}
//3.将集合数组从大到小赋值给新集合。因为可能r数组中的某些值为null,故要进行该操作
/**
* 用StringBuilder,StringBuffer,List 三种方法存储字符
* string创建的字符串,创建后不能改变
* StringBuilder,StringBuffer创建的字符串可以改变,
* 改变后最终可以用toString()方法转换为不变的字符串,
*
* 采用官方提供的方法:append()、insert()、reverse()、setCharAt()、setLength()
* 区别:StringBuilder线程不安全,执行速度块
* StringBuffer 线程安全,执行速度慢
*/
StringBuilder stringBuilder = new StringBuilder();
StringBuffer stringBuffer = new StringBuffer();
List<Character> results = new ArrayList<>();
for (int i = frequencyBucket.length-1;i >= 0;i--){
if (frequencyBucket[i] == null)
continue;
for (char c: frequencyBucket[i]){
for (int j=0;j<i;j++){
stringBuilder.append(c);
stringBuffer.append(c);
results.add(c);
}
}
}
System.out.println("用stringBuilder对象存储字符:"+stringBuilder.toString());
System.out.println("用stringBuffer对象存储字符:" + stringBuffer.toString());
System.out.println("用list结合存储字符:" + results);
}
}