日期:2014-05-20 浏览次数:20734 次
public static void main(String[] args) { String str = "ahadcdffhachaasdfaweadbastawetaesartaw"; // 准备 char[] cTarget = str.toLowerCase().toCharArray(); // 转为char数组 int[] cnts = new int[26]; // 计数器 // 检索 for (char c : cTarget) { cnts[c - 'a']++; } // 排序前准备下用于记录位置的数组 char[] cs = new char[26]; for (char i = 0; i < cs.length; i++) { cs[i] = (char) ('a' + i); } // 排序 for (int i = 0; i < cnts.length; i++) { for (int j = i + 1; j < cs.length; j++) { if (cnts[j] < cnts[i]) { int a = cnts[j]; cnts[j] = cnts[i]; cnts[i] = a; char c = cs[j]; cs[j] = cs[i]; cs[i] = c; } } } // 最后输出 for (int i = 0; i < cs.length; i++) { if (cnts[i] > 0) { System.out.println(cs[i] + ":" + cnts[i] + "\t"); } } }
------解决方案--------------------
期待更短的。。。
String str = "ahadcdffhacha"; Map map = new HashMap(); for(int i = 0;i < str.length();i++) { if(map.containsKey(str.charAt(i))) { map.put(str.charAt(i), Integer.parseInt(map.get(str.charAt(i)).toString())+1); } else { map.put(str.charAt(i), 1); } } List list = new ArrayList(); Set set = map.entrySet(); for(Iterator i = set.iterator();i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); list.add(entry); } Collections.sort(list,new Comparator() { public int compare(Object o1, Object o2) { Map.Entry e1 = (Map.Entry)o1; Map.Entry e2 = (Map.Entry)o2; return Integer.parseInt(e1.getValue().toString())-Integer.parseInt(e2.getValue().toString()); } }); System.out.println(list);