题解 | #字符统计#

字符统计

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        String s = in.nextLine();
        char[] cs = s.toCharArray();
        int len = cs.length;
        List<Node> list = new ArrayList<>();
        for (int i = 0; i < len; i++) {
            char c = cs[i];
            boolean exit = false;
            for (int j = 0; j < list.size(); j++) {
                Node node = list.get(j);
                if (c == node.c) {
                    node.count++;
                    exit = true;
                }
            }
            if (!exit) {
                list.add(new Node(c));
            }
        }
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i).c);
        }
    }
}

class Node implements Comparable<Node>{
    char c;
    int count = 0;
    Node (char c) {
        this.c = c;
    }
    public int compareTo(Node node) {
        if (this.count == node.count) {
            return this.c - node.c;
        } else {
            return node.count - this.count;
        }
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务