package com.learn.mianshi;
import java.util.*;
public class StrNum {
public static void main(String[] args) {
String str = "abdc2223333ddd";
test(str);
}
public static void test(String str) {
if (null == str) {
return;
}
char[] charArray = str.toCharArray();
Map<Character,Integer> map = new TreeMap<>(new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
return o2-o1;
}
});
for (char c : charArray) {
if (map.containsKey(c)) {
Integer i = map.get(c);
if (null != i) {
i++;
}
map.put(c,i);
} else {
map.put(c,1);
}
}
//构建数组存储键值,然后进行排序
char[] arrKey = new char[map.size()];
int[] arrValue = new int[map.size()];
int k1 = -1, k2 = -1;
for (Map.Entry<Character,Integer> entry : map.entrySet()) {
arrKey[++k1] = entry.getKey();
arrValue[++k2] = entry.getValue();
}
//对arrValue进行从大到小的排序,使用选择排序
for(int i = 0; i < arrValue.length - 1; i++){
int tempmax = arrValue[i];
int index = i;
for(int j = i+1; j < arrValue.length; j++){
if(tempmax < arrValue[j]){
tempmax = arrValue[j];
index= j;
}
}
//选出第一个最大值,依次交换位置
int temp = arrValue[i];
char temp1 = arrKey[i];
arrValue[i] = arrValue[index];
arrKey[i] = arrKey[index];
arrValue[index] = temp;
arrKey[index] = temp1;
}
for(int i = 0; i < arrValue.length; i++){
System.out.print(" "+arrKey[i]+":"+arrValue[i]+";");
}
}
}
输出:d:4; 3:4; 2:3; a:1; c:1; b:1;