字符统计及重排
标题:字符统计及重排 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
给出一个仅包含字母的字符串,不包含空格,统计字符串中各个字母(区分大小写)出现的次数,并按照字母出现次数从大到小的顺序输出各个字母及其出现次数。如果次数相同,按照自然顺序进行排序,且小写字母在大写字母之前。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] dataArray = sc.nextLine().split("");
Map<String,Integer> dataMap = new HashMap<>();
for (String d : dataArray) {
if(dataMap.containsKey(d)) {
dataMap.put(d,dataMap.get(d)+1);
} else {
dataMap.put(d,1);
}
}
List<ZiMu> ziMuList = new ArrayList<>();
for (String data : dataMap.keySet()) {
ziMuList.add(new ZiMu(data, dataMap.get(data)));
}
ziMuList.sort(new Comparator<ZiMu>() {
@Override
public int compare(ZiMu o1, ZiMu o2) {
int ca = o2.count - o1.count;
if (ca == 0) {
int ch1 = o1.ziMu.charAt(0);
int ch2 = o2.ziMu.charAt(0);
if(ch1 >= 'A' && ch1 <= 'Z') {
ch1 = ch1 + 100;
}
if(ch2 >= 'A' && ch2 <= 'Z') {
ch2 = ch2 + 100;
}
return ch1 - ch2;
} else {
return ca;
}
}
});
StringBuilder result = new StringBuilder();
for (ZiMu z : ziMuList) {
result.append(z.ziMu).append(":").append(z.count).append(";");
}
System.out.println(result);
}
static class ZiMu{
String ziMu;
int count;
public ZiMu(String ziMu,int count) {
this.ziMu = ziMu;
this.count = count;
}
}
}

查看26道真题和解析