Problem Description
求任意给定字符串中出现次数最多的字符,如果出现最多次数的字符有多个,则只输出最先出现的字符。
Input Description
输入任意一个字符串(不超过100个字符)
Output Description
输出出现次数最多的字符。
Sample Input
this is c++ program
Sample Output
i
源码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] str = sc.nextLine().split("");//读入一行
Map<String, Integer> map = new LinkedHashMap<>();//双列集合LinkedHashMap有序,字符串中的字符为键,出现次数为值
for (String s : str) {//键找值,遍历双列集合
if (map.containsKey(s)) {//键已经存在,更改值
int n = map.get(s);
map.put(s, n + 1);
} else {//键不存在,直接添加
map.put(s, 1);
}
}
Set<String> keys = map.keySet();//键构成单列集合
int maxn = 0;//存放最大的值
String temp = null;//存放最大的值对应的键
for (String key : keys) {
// System.out.println(key+"----"+map.get(key));
if (key.equals(" "))//跳过空白字符
continue;
if (map.get(key) > maxn) {//找最大的值
maxn = map.get(key);
temp = key;
}
}
System.out.println(temp);
}
}
测试结果