forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement Magic Dictionary.java
40 lines (32 loc) · 1.01 KB
/
Implement Magic Dictionary.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
class MagicDictionary {
private String[] dictionary;
public MagicDictionary() {}
public void buildDict(String[] dictionary) {
this.dictionary = dictionary;
}
public boolean search(String searchWord) {
for (String dictWord: this.dictionary) {
if (this.match(searchWord, dictWord, 1))
return true;
}
return false;
}
private boolean match(String s, String t, int expectedDiff) {
if (s.length() != t.length())
return false;
int diff = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != t.charAt(i))
diff++;
if (diff > expectedDiff)
return false;
}
return diff == expectedDiff;
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dictionary);
* boolean param_2 = obj.search(searchWord);
*/