题解 | #字符统计#--数组实现次数降序和ASCII码升序

字符统计

https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            char[] chArr = str.toCharArray();
            int[] temp = new int[150];
            // 记录字符出现的次数并按ASCII码升序
            for (int i = 0; i < chArr.length; i++) {
                temp[chArr[i]]++;
            }
            // 找出最大次数
            int max = 0;
            for (int j = 0; j < temp.length; j++) {
                if (max < temp[j]) {
                    max = temp[j];
                }
            }
            // 按次数倒叙输出
            StringBuilder sbf = new StringBuilder();
            while (max != 0) {
                for (int j = 0; j < temp.length; j++) {
                    if (temp[j] == max) {
                        sbf.append((char)j);
                    }
                }
                max--;
            }
            System.out.println(sbf.toString());
        }

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务