面试常用的JAVA的简单算法题目,例题:
给定一串英文取出出现次数前三的字母,下面是代码演示:
public static void main (String args[]) {
String s = "inne putn extL ine";
s = s.replace(" ", "");
//将字符串转换成字符数组
char[] arr = s.toCharArray();
//定义双列集合,存储字符串字符以及字符出现的次数
HashMap<Character, Integer> hm = new HashMap<>();
for (char c : arr) {
//如果集合中不包含这个键,就将该字符当作键,值为1存储,如果集合中包含这个键,就将值增加1存储
if (!hm.containsKey(c)) {
hm.put(c, 1);
} else
hm.put(c, hm.get(c) + 1);
}
for (Character key : hm.keySet()) {//hm.keySet()代表所有键的集合
if (hm.get(key) > 1)//hm.get(key)根据键获取值
System.out.println(key + "=" + hm.get(key));
}
}