Problem
Design a method to find the frequency of occurrences of any given word in a book.
Examples
Example 1:
Input:
BookFrequency(String text)
text =
the day is sunny the the
the sunny is is
Input:
getFrequency("the")
Output: 4
Input:
getFrequency("is")
Output: 3
Here is similar problem with bash
script: Word Frequency from File.
Solution
Method 1 - Using Hashmap
Just scan the word, trim it and put in HashMap. Now, when searching lower case it and search it.
class Book {
private Map<String, Integer> map;
public Book(String[] book) {
map = new HashMap<>();
for (String word: book) {
word = word.toLowerCase();
if (word.trim() != "") {
map.put(word, map.getOrDefault(word, 0) + 1);
}
}
public getFrequency(String word) {
word = word.toLowerCase();
return map.getOrDefault(word, 0);
}
}