我熟悉ascii的问题。问题是我没有unicode字符相同问题的经验。例如,如果给出包含单词的字符串数组,如何返回最常出现的单词?提前谢谢!
p.s。:你总是可以使用长度为" 256"表示ASCII中的所有字符,而在unicode中则不能这样做。 HashMap是必须的,也是解决问题的最佳方法吗?我听说有更好的方法来解决它。以下是我能想到的:
String str = "aa df ds df df"; // assume they are Unicode
String[] words = str.split(" ");
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String word : words){
if (map.containsKey(word)){
int f = map.get(word);
map.put(word, f+1);
} else{
map.put(word, 1);
}
}
int max = 0;
String maxWord = "";
for (String word : words){
int f = map.get(word);
if (f > max){
max = f;
maxWord = word;
}
}
System.out.println(maxWord + " " +max);
答案 0 :(得分:0)
// Inspired by GameKyuubi. It can be solved using array sort and count the most frequently used word using constatnt space.
Arrays.sort(words);
int max = 0;
int count = 0;
String maxWord = "";
String prev = "";
for (String word : words){
if (prev.equals("") || word.equals(prev)){
count++;
} else{
count = 1;
}
if (max < count){
max = count;
maxWord = word;
}
prev = word;
}
System.out.println(maxWord + " " +max);