-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathImplementMagicDictionary.java
More file actions
67 lines (58 loc) · 2 KB
/
ImplementMagicDictionary.java
File metadata and controls
67 lines (58 loc) · 2 KB
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
package com.dbc;
import java.util.*;
public class ImplementMagicDictionary {
private final Map<Integer, List<String>> map;
private final Map<String, Integer> count;
private final Set<String> set;
public ImplementMagicDictionary() {
this.map = new HashMap<>();
this.count = new HashMap<>();
this.set = new HashSet<>();
}
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
if (!this.map.containsKey(word.length())) {
this.map.put(word.length(), new ArrayList<>());
}
this.map.get(word.length()).add(word);
}
}
public boolean search(String searchWord) {
if (!this.map.containsKey(searchWord.length())) {
return false;
}
for (String word : this.map.get(searchWord.length())) {
int count = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != searchWord.charAt(i)) count++;
}
if (count == 1) return true;
}
return false;
}
private List<String> gen_neighbor(String word) {
List<String> res = new ArrayList<>();
for (int i = 0; i < word.length(); i++) {
char[] charWord = word.toCharArray();
charWord[i] = '*';
res.add(Arrays.toString(charWord));
}
return res;
}
public void buildDict1(String[] dictionary) {
for (String word : dictionary) {
this.set.add(word);
for (String gen_word : gen_neighbor(word)) {
this.count.put(gen_word, this.count.getOrDefault(gen_word, 0) + 1);
}
}
}
public boolean search1(String searchWord) {
for (String gen_word : gen_neighbor(searchWord)) {
if (this.count.getOrDefault(gen_word, 0) > 1 ||
this.count.getOrDefault(gen_word, 0) == 1 && !this.set.contains(searchWord))
return true;
}
return false;
}
}