黑马程序员技术交流社区
标题:
答题奖4技术分(需完整代码) !另一种思路分享
[打印本页]
作者:
王洪波
时间:
2013-5-12 20:16
标题:
答题奖4技术分(需完整代码) !另一种思路分享
题目: 已有字符串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());
复制代码
作者:
大漠孤烟
时间:
2014-4-27 14:21
新手,学习啦、、、
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2