-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindCommonCharacters.java
52 lines (44 loc) · 1.52 KB
/
FindCommonCharacters.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
class Solution {
public List<String> commonChars(String[] words) {
// using the shortest word for optimization. any word can be used here
HashMap<String, Integer> w = getWordMap(getShortestWordInList(words));
HashMap<String, Integer> tempWord;
for (String word : words){
tempWord = getWordMap(word);
for (String k : w.keySet()){
w.put(k, Math.min(
w.getOrDefault(k, 0),
tempWord.getOrDefault(k, 0)
));
}
}
List<String> res = new ArrayList<>();
Iterator<Map.Entry<String, Integer>> it = w.entrySet().iterator();
Map.Entry<String, Integer> pair;
while (it.hasNext()){
pair = it.next();
for (int i = 0; i < pair.getValue(); i++)
res.add(pair.getKey());
}
return res;
}
private HashMap<String, Integer> getWordMap(String word){
String temp;
int freq;
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < word.length(); i++){
temp = String.valueOf(word.charAt(i));
freq = map.getOrDefault(temp, 0);
map.put(temp, freq + 1);
}
return map;
}
private String getShortestWordInList(String[] words){
String minWord = words[0];
for (String word : words){
if (word.length() < minWord.length())
minWord = word;
}
return minWord;
}
}