字符統計

題目描述

若是統計的個數相同,則按照ASII碼由小到大排序輸出 。若是有其餘字符,則對這些字符不用進行統計。
實現如下接口:
    輸入一個字符串,對字符中的各個英文字符,數字,空格進行統計(可反覆調用)
    按照統計個數由多到少輸出統計結果,若是統計的個數相同,則按照ASII碼由小到大排序輸出
    清空目前的統計結果,從新統計
調用者會保證:
輸入的字符串以‘\0’結尾。

輸入描述

輸入一串字符。

輸出描述

對字符中的
各個英文字符(大小寫分開統計),數字,空格進行統計,並按照統計個數由多到少輸出,若是統計的個數相同,則按照ASII碼由小到大排序輸出 。
若是有其餘字符,則對這些字符不用進行統計。

輸入例子

aadddccddc

輸出例子

dca

算法實現

import java.util.*;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            System.out.println(count(input));
        }

        scanner.close();
    }

    private static String count(String s) {

        Set<Node> set = new TreeSet<>(new Comparator<Node>() {
            @Override
            public int compare(Node t, Node s) {

                if (t.v != s.v) {
                    return s.v - t.v;
                }

                return t.c - s.c;
            }
        });

        Map<Character, Node> map = new HashMap<>(s.length());

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c ==' ') {
                if (map.containsKey(c)) {
                    map.get(c).v++;
                } else {
                    map.put(c, new Node(c, 1));
                }
            }
        }


        for (Node n : map.values()) {
            set.add(n);
        }

        StringBuilder builder = new StringBuilder(set.size());
        for (Node n : set) {
            builder.append(n.c);
        }

        return builder.toString();
    }

    private static class Node {
        private char c;
        private int v;

        public Node(char c, int v) {
            this.c = c;
            this.v = v;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Node node = (Node) o;

            return c == node.c;

        }

        @Override
        public int hashCode() {
            return (int) c;
        }
    }
}
相關文章
相關標籤/搜索