题目: 已有字符串str1="sdfg,hellozx,sdfcv-waadfa,fsasdfxcvdf"
*
* 键盘输入任意字符串,例如:String str2="HaHahello01",
*
* 在原来字符串str1中去掉str2中最大的交集字符串(hello)后, 获取该字符串str1中的每个字母出现的次数。
*
* 例如:去掉hello后
*
* 以这种方式打印:按字母出现次数排序,次数相同时,按字母从大到小排序!
*
* 输出:f(出现6次)d(出现5次)s(出现4次)x(出现2次)v(出现2次)c(出现2次)w(出现1次)g(出现1次)- String str1="sdfg,hellozx,sdfcv-waadfa,fsasdfxcvdf";
- String str2="HaHahello01";
-
- //构造str1的字符集合
- char[] chs1 = str1.toCharArray();
- Collection<Character> c1 = new ArrayList<Character>();
- for(char ch : chs1)
- c1.add(ch);
- System.out.println(c1);
- //构造str2的字符集合
- char[] chs2 = str2.toCharArray();
- Collection<Character> c2 = new ArrayList<Character>();
- for(char ch : chs2)
- c2.add(ch);
- //System.out.println(c2);
- //求差集
- c1.removeAll(c2);
- //System.out.println(c1.size());
-
- //向hashMap中存,并记数
- Map<Character,Integer> map = new HashMap<Character,Integer>();
- Integer value;
- for(Character ch : c1)
- {
- if(!(ch>=97 && ch<=122 || ch>=65 && ch<=90))
- continue;
- value = map.get(ch);
- if(null==value)
- value=0;
- map.put(ch, ++value);
- }
-
- Set<Map.Entry<Character,Integer>> set = new TreeSet<Map.Entry<Character,Integer>>(new Comparator<Map.Entry<Character,Integer>>(){
- @Override
- public int compare(Entry<Character, Integer> o1,
- Entry<Character, Integer> o2)
- {
- Character ch1 = o1.getKey();
- Integer cnt1 = o1.getValue();
- Character ch2 = o2.getKey();
- Integer cnt2 = o2.getValue();
- int rv = cnt2.compareTo(cnt1);
- if(0 != rv) return rv;
- return ch2.compareTo(ch1);
- }});
-
- for(Map.Entry<Character,Integer> entry : map.entrySet())
- {
- set.add(entry);
- }
- //System.out.println(set.size());
- StringBuilder sb = new StringBuilder();
- for(Entry<Character,Integer> entry : set)
- {
- Character ch = entry.getKey();
- Integer cnt = entry.getValue();
- sb.append(ch).append("(出现了").append(cnt).append("次)");
- }
- System.out.println(sb.toString());
复制代码 |
|