题目

假设有一个字符串,字符串内部的所有字符都是在ascii编码的范围内,编码求出字符串中出现频率最高的字符,如果频率最高的字符有几个字符出现的频率一样,则输出最先出现的字符。

如输入串为 “hello world, every body!”,则输出频率最高且最先出现的字符。

方法定义:char getMaxOccurChar(String str)

输入

hello world, every body!

输出

e

代码

方法一:用LinkedHashMap模拟一下,最后求出最值即可

public class Main {

public static void main(String[] args) {
char result = getMaxOccurChar("hello world, every body!");
System.out.println(result);
result = getMaxOccurChar("aaaahfdfbbbbbbbbbb");
System.out.println(result);
}

public static char getMaxOccurChar(String str) {

int maxCount = 1;
Character result = new Character(str.charAt(0));

Map<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < str.length(); i++) {
Character content = str.charAt(i);
Integer count = map.get(content);
if (count == null) {
map.put(content, 1);
} else {
map.put(content, count + 1);
}
}

for (Map.Entry<Character, Integer> entry: map.entrySet()) {
if (entry.getValue() > maxCount) {
result = entry.getKey();
maxCount = entry.getValue();
}
}
return result;
}
}

面试官:有没有可能一次遍历搞定呢?
我:可以(然后没写出来)
面试官:倒着遍历可以吗?
我:哦,对

public class Main {

public static void main(String[] args) {
char result = getMaxOccurChar("hello world, every body!");
System.out.println(result);
result = getMaxOccurChar("aaaahfdfbbbbbbbbbb");
System.out.println(result);
}

public static char getMaxOccurChar(String str) {

int maxCount = 1;
Character result = new Character(str.charAt(0));
Map<Character, Integer> map = new LinkedHashMap<>();

for (int i = str.length() - 1; i >= 0 ; i--) {
Character content = str.charAt(i);
Integer count = map.get(content);
if (count == null) {
map.put(content, 1);
count = 1;
} else {
map.put(content, count + 1);
count += 1;
}
if (count >= maxCount) {
maxCount = count;
result = str.charAt(i);
}
}
return result;
}
}