TreeMap -- 如何查找以字母表中的每个字母开头的单词数

TreeMap -- How to find the number of words that begin with each letter of the alphabet

所以我有一个单词列表。例如,{Apple, Available, Art, Between, Beyond, Door, Drive, ......}

我想显示以每个字母开头的单词数,所以结果应该是 A = 3, B = 2, D = 2, ......

这是我写的代码,但显然它没有按照我想要的方式工作。

    Map<String, Integer> myMap = new TreeMap<String, Integer>();

    for (int i = 0; i < theWords.length; i++) {
        for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
            int numOfWords = 0;
            char firstLetter = theWords[i].charAt(0);
            if (firstLetter == alphabet) {
                myMap.put(String.valueOf(alphabet), numOfWords + 1);
            }
        }   
    }
    System.out.println(myMap);

这就是我得到的结果...

{A=1, B=1, C=1, D=1, E=1, F=1, G=1, H=1, J=1, K=1, L=1, M=1, N=1, O=1, P=1, Q=1, R=1, S=1, T=1, U=1, W=1, Y=1}

P.S。我必须使用 TreeMap。

你在内部循环中设置了 int numOfWords = 0; - 就是这样。 这就是它总是 1 放在地图

中的原因

不是双循环,而是获取第一个字符并添加到 Map。

类似于:

for (String fruit : theFruits) {
  String firstLetter = fruit.substring(0, 1);
  Integer count = myMap.get(firstLetter);
  if (count == null) {
    myMap.put(firstLetter, 1);
  }
  else {
    myMap.put(firstLetter, ++count);
  }
}

Map 映射键和值,其中键是唯一的。

  1. 创建地图。
  2. 对于列表中的每个单词,获取第一个字符。
  3. 查看获取的字符是否存在于地图的键集中。
  4. 如果存在,则只需增加该键的计数,否则在映射中创建一个新条目并将计数保持为 1。

对于您的问题,您可以简单地使用一个大小为 26 的 int 类型的数组。这将作为您的地图。

第 0 个索引用于 a,第 1 个索引用于 b,依此类推直到第 25 个索引用于 z

现在应用上面的逻辑

例如,如果单词列表是

String[] wordList = { "apple", "mango", "berry", "rice", "banana"} ;

int [] map = new int [26]; //by default all elements initialized with 0
for(int i =0; i < wordList.length; i++){
     char first = wordList[i].charAt(0);
     int index = first - 'a';
     map[index] = map[index] + 1;
}

假设:单词是小写的,每个单词只由26个小写英文字母组成,所有单词都是唯一的。如果有额外的字符,数组的大小需要修改,对于重复的数组,可以用 Hashmap 替换,但算法步骤与上面提到的相同

P.S。通常对于前缀搜索,Trie 是首选解决方案。