Java Unicode字符

Java Unicode字符,java,unicode,Java,Unicode,我熟悉ascii的问题。问题是我没有在unicode字符中遇到相同问题的经验。例如,如果给定一个包含单词的字符串数组,如何返回最常出现的单词?提前谢谢 p、 s:您可以始终使用长度为“256”的数组来表示ASCII中的所有字符,但对于unicode,您不能这样做。HashMap是解决这个问题的一个必须的和最好的方法吗?我听说有更好的办法来解决这个问题。以下是我能想到的: String str = "aa df ds df df"; // assume they are Unicode

我熟悉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);
String str=“aa-df-ds-df”;//假设它们是Unicode
String[]words=str.split(“”);
HashMap=newHashMap();
for(字符串字:字){
if(地图容器(word)){
intf=map.get(word);
地图放置(字,f+1);
}否则{
地图放置(单词1);
}
}
int max=0;
字符串maxWord=“”;
for(字符串字:字){
intf=map.get(word);
如果(f>最大值){
max=f;
maxWord=word;
}
}
System.out.println(maxWord+“”+max);
//灵感来自GameKyuubi。可以使用数组排序来解决此问题,并使用constatnt空间计算最常用的单词。
数组。排序(单词);
int max=0;
整数计数=0;
字符串maxWord=“”;
字符串prev=“”;
for(字符串字:字){
if(prev.equals(“”)| word.equals(prev)){
计数++;
}否则{
计数=1;
}
如果(最大值<计数){
最大值=计数;
maxWord=word;
}
prev=单词;
}
System.out.println(maxWord+“”+max);

如果使用ASCII或Unicode,该问题会有什么不同?@TedHopp您始终可以使用长度为“256”的数组来表示ASCII中的所有字符,而对于Unicode,则不能这样做。HashMap是解决这个问题的一个必须的和最好的方法吗?我听说有更好的办法来解决这个问题,也完全一样。它甚至不需要是单词,它可以是任何东西的数组,您可以通过在对象中实现comparable(该字符串已经实现了,所以您甚至不需要这样做),然后使用CompareTo()以完全相同的方式返回数组中最常用的对象.我不知道如何使用长度为256的数组来解决“最常用词”问题。我同意存在一些问题,ASCII编码的小尺寸使事情更简单,但问题不在其中。每个问题都是不同的;没有具体的东西,很难提供建议。@GameKyuubi你能用你的方法解决这个问题吗?我在帖子中添加了我的代码,hashmap是我所能想到的:(这避免了
hashmap
,但代价是创建一个O(n logn)算法(因为排序),而不是一个O(n)。
// 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);