日期:2014-05-17  浏览次数:20823 次

算法求解String str = "A,B,C,A,B,A";
String str = "A,B,C,A,B,A";
要求用效率高的方法输出
A:3
B:2
C:1

------解决方案--------------------
Java code

    public static void main(String[] args) {
        String str = "A,B,C,A,B,A";

        Map<String, Integer> tm = new TreeMap<String, Integer>();
        String[] words = str.split(",");
        
        for (final String s : words) {
            if (!s.isEmpty()) {
                if (!tm.containsKey(s)) {
                    tm.put(s, 1);
                } else {
                    tm.put(s, tm.get(s).intValue() + 1);
                }                
            }
        }
        for (Map.Entry<String, Integer> entry : tm.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }