2014-04-08 81 views
-1

我熟悉ascii的问题。问题是我对unicode字符中的同样问题没有经验。例如,如何返回给定包含单词的字符串数组最常出现的单词?提前致谢!Java 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); 
+1

怎么样这个问题将与ASCII或Unicode有什么不同? –

+0

@TedHopp您可以随时使用长度为“256”的数组来表示ASCII中的所有字符,而在unicode中则无法这样做。 HashMap是否是解决问题的最佳方法?我听说有更好的方法来解决它。 –

+0

这完全一样。它甚至不需要是单词,它可以是任何数组的数组,并且可以通过在对象中实现可比较的方式以完全相同的方式返回数组中最常用的对象(该String已经实现,因此, t甚至需要这样做),然后使用CompareTo()。 – GameKyuubi

回答

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); 
+0

这样做避免了一个'Hashmap',但代价是创建一个O(n log n)算法(因为排序)而不是O (n)。 –

+0

是的,优点和缺点 –