[color=blue]
关于Map.Entry可以参看[url=http://ocaicai.iteye.com/admin/blogs/794922]在容器中使用增强的for循环,简洁大气,结构清晰[/url]所以说是:英雄所见略同哈。
不足之处就是:当有两个或者多个最大的时候,会发生覆盖。
第一个例子:
[/color]
[color=blue]
第二个例子:
[/color]
.
关于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
.