Cracking Coding Interview - 16.2 Word Frequencies

Word Frequencies: Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiple times?

Hints: #489, #536

解法

代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
Map<String, Integer> cache = new HashMap<>();

public void prepare() {  
  File book = ...;
  while (book not eof) {
    String line = book.readLine();
    String[] words = line.split("[^\\w]");
    for (String word : words) {
      if (!cache.contains(word)) {
        cache.put(word, 0);
      }
      cache.put(word, cache.get(word) + 1);
    }
  }
}

public int wordFreq(String word) {
  if (!cache.contains(word)) {
    cache.put(word, 0);
  }
  return cache.get(word);
}

版权

评论