题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
我只会笨办法,先计算数量,根据数量重新拼接字符,当有相同数量的字符时,转成char数组,再排序,最后再拼接所有的输出。
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str = in.nextLine();
if (str.length() < 1 || str.length() > 1000) {
System.out.println("ERROR");
continue;
}
char[] chs = str.toCharArray();
Map<String, Integer> countMap = new HashMap<>();
for (int i = 0; i < chs.length; i++) {
String sch = "" + chs[i];
Integer ioch = countMap.get(sch);
if (ioch == null) {
countMap.put(sch, 1);
} else {
countMap.put(sch, ioch + 1);
}
}
List<Integer> countList = new ArrayList<>(countMap.values());
Collections.sort(countList);
// 去重
countList = countList.stream().distinct().collect(Collectors.toList());
StringBuilder sb = new StringBuilder();
for (int i = countList.size() - 1; i >= 0; i--) {
int strLen = countList.get(i);
// 拼接重复数量的字符,进行排序
StringBuilder sortSb = new StringBuilder();
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
String chi = entry.getKey();
Integer chc = entry.getValue();
if (chc == strLen) {
sortSb.append(chi);
}
}
char[] sortCh = sortSb.toString().toCharArray();
Arrays.sort(sortCh);
sb.append(new String(sortCh));
}
System.out.println(sb);
}
}
}

