假設有一個字符串,字符串內部的所有字符都是在ascii編碼的範圍內,編碼求出字符串中出現頻率最高的字符,如果頻率最高的字符有幾個字符出現的頻率一樣,則輸出最先出現的字符。
如輸入串爲 “hello world, every body!”,則輸出頻率最高且最先出現的字符。
方法定義:char getMaxOccurChar(String str)
輸入:hello world, every body!
輸出:e
輸入:aaaahfdfbbbbbbbbbb
輸出:b
在算法愛好者 貼出的思路
public class Main {
public static void main(String[] args) {
char result = getMaxOccurChar("hello world, every body!");
// e
System.out.println(result);
result = getMaxOccurChar("aaaahfdfbbbbbbbbbb");
// b
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;
}
}
我想到另一種只需一次遍歷的思路
private static char getMaxOccurChar(String str) {
char[] chars = str.toCharArray();
int minIndex = 0;
int maxCount = 0;
for(int x = 0; x < chars.length; x++){
Pattern compile = Pattern.compile(String.valueOf(chars[x]));
Matcher matcher = compile.matcher(str);
int count = 0;
while(matcher.find()){
count++;
}
//數量大於
if(count > maxCount){
maxCount = count;
minIndex = x;
}
//數量一致
else if(count == maxCount && minIndex > x){
minIndex = x;
}
}
return chars[minIndex];
}