题目:输入一个字符串,统计出现的最多次数的字符;
输入:ababcacdAABCD
String a = " ababcacdAABCD ".trim();
Set<Object> set = new HashSet<>();
Map<Character, Integer> map = new HashMap<>();
int max = 0;
char result = 0;
for (int i = 0; i <a.length() ; i++) {
char c = a.charAt(i);
boolean add = set.add(c);//利用set特性,不重复
if (add){
map.put(c,1);
}else {
//重复计数
if (map.containsKey(c)){
Integer integer = map.get(c);
map.put(c,integer+1);
}
}
}
//排序
List<Map.Entry<Character, Integer>> entries = new ArrayList<>(map.entrySet());
for (Map.Entry<Character, Integer> entry : entries) {
if (entry.getValue()>max){
max = entry.getValue();
result = entry.getKey();
}
}
System.out.println("出现次数最多的字符:"+result+";次数:"+max);
输出:出现次数最多的字符:a;次数:3