Problem#
Design a method to find the frequency of occurrences of any given word in a book.
Examples#
Example 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.
Code#
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
}
}