-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordProcessor.java
75 lines (59 loc) · 2.38 KB
/
WordProcessor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.*;
public class WordProcessor {
private List<Character> wordSeperators;
private List<Character> sentenceTerminators;
private boolean caseSensitive;
public WordProcessor(List<Character> wordSeperators, List<Character> sentenceTerminators, boolean caseSensitive) {
this.wordSeperators = wordSeperators;
this.sentenceTerminators = sentenceTerminators;
this.caseSensitive = caseSensitive;
}
public List<String> getMostFrequentWords(String str) {
if (str == null || str.isEmpty()) {
return new ArrayList<>();
}
return getMostFrequentWords(buildWordFrequencyMap(str.trim()));
}
public HashMap<String, Integer> buildWordFrequencyMap(String str) {
HashMap<String, Integer> wordFrequency = new HashMap<>();
if (str == null || str.isEmpty()) {
return wordFrequency;
}
int start = 0, current = 0;
for (; current < str.length(); current++) {
if (wordSeperators.contains(str.charAt(current)) || sentenceTerminators.contains(str.charAt(current))) {
updateWordFrequency(wordFrequency, str.substring(start, current));
start = current + 1;
}
}
updateWordFrequency(wordFrequency, str.substring(start, current));
return wordFrequency;
}
private List<String> getMostFrequentWords(HashMap<String, Integer> wordFrequencyMap) {
int maxFrequency = 0;
for (Map.Entry<String, Integer> entry : wordFrequencyMap.entrySet()) {
if (entry.getValue() > maxFrequency) {
maxFrequency = entry.getValue();
}
}
List<String> mostFrequentWords = new ArrayList<>();
for (Map.Entry<String, Integer> entry : wordFrequencyMap.entrySet()) {
if (entry.getValue().intValue() == maxFrequency) {
mostFrequentWords.add(entry.getKey());
}
}
return mostFrequentWords;
}
private void updateWordFrequency(HashMap<String, Integer> wordFrequency, String word) {
if (word == null || word.isEmpty()) {
return;
}
if (!caseSensitive) {
word = word.toLowerCase();
}
if (!wordFrequency.containsKey(word)) {
wordFrequency.put(word, 0);
}
wordFrequency.put(word, wordFrequency.get(word) + 1);
}
}