给你一个字符串,包含了空格等标点符号,要你计算出出现次数最多的字母和该字母出现的次数。 ...

[color=blue]
关于Map.Entry可以参看[url=http://ocaicai.iteye.com/admin/blogs/794922]在容器中使用增强的for循环,简洁大气,结构清晰[/url]所以说是:英雄所见略同哈。

不足之处就是:当有两个或者多个最大的时候,会发生覆盖。

第一个例子:
[/color]


package mapApp;

import java.util.HashMap;
import java.util.Map;

public class MaxTimesOfChar2 {
/*
* 主要是对MaxTimesOfChar.java的瘦身,思路都是英雄所见略同
*
* */
public static void main(String[] args) {
Map<Character, Long> charTimesMap = new HashMap<Character, Long>();

String str = "hello wolrd wlllkdsfhksadfls?sdfsak lsdfjsidf jsafdalsjfs sfskdfjs";
str = str.replaceAll("[^a-zA-Z]", "");// 过滤掉非字母
for (char each : str.toCharArray()){
Long freq = charTimesMap.get(each);
charTimesMap.put(each, freq == null ? 1 : freq + 1);
}

char maxAppearChar = 0;
Long maxAppearTimes = 0l;
for (Map.Entry<Character, Long> charAppear : charTimesMap.entrySet()) {
if (charAppear.getValue() > maxAppearTimes) {
maxAppearChar = charAppear.getKey();
maxAppearTimes = charAppear.getValue();
}
}
System.out.println("出现最多的字母:" + maxAppearChar);
System.out.println("出现次数:" + maxAppearTimes);

}
}
输出结果:
出现最多的字母:s
出现次数:13


[color=blue]
第二个例子:
[/color]

package mapApp;

public class MaxTimesOfChar3 {
public static void main(String[] args) {
String s = "abbcccddddeeeeeeffffff(*&*&*(*&%%";
s = s.replaceAll("[^a-zA-Z]", "");// 过滤掉非字母
System.out.println(s);// 测试用
int max = 0;// 保存最大次数
int temp = 0;
String maxString = "";// 保存最大次数的那个字符
String tempString = "";
while (s.length() > 0) {
tempString = s.substring(0, 1);// 取得字符串的第一个字符
System.out.println(tempString);// 测试用
String subs = s.replace(tempString, "");
temp = s.length() - subs.length();
if (max <= temp) {
max = temp;
maxString = tempString;
}
s = subs;
System.out.println(temp + "--" + s);// 测试用
}
System.out.println(maxString + " max= " + max);
}
}
输出结果:
abbcccddddeeeeeeffffff
a
1--bbcccddddeeeeeeffffff
b
2--cccddddeeeeeeffffff
c
3--ddddeeeeeeffffff
d
4--eeeeeeffffff
e
6--ffffff
f
6--
f max= 6




.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值