Implement Magic Dictionary LeetCode solution in Java

1
class MagicDictionary {
2
private String[] dictionary;
3

4
public MagicDictionary() {}
5

6
public void buildDict(String[] dictionary) {
7
this.dictionary = dictionary;
8
}
9

10
public boolean search(String searchWord) {
11
for (String dictWord : this.dictionary) {
12
if (this.match(searchWord, dictWord, 1)) return true;
13
}
14

15
return false;
16
}
17

18
private boolean match(String s, String t, int expectedDiff) {
19
if (s.length() != t.length()) return false;
20

21
int diff = 0;
22
for (int i = 0; i < s.length(); i++) {
23
if (s.charAt(i) != t.charAt(i)) diff++;
24
if (diff > expectedDiff) return false;
25
}
26

27
return diff == expectedDiff;
28
}
29
}
30

31
/**
32
* Your MagicDictionary object will be instantiated and called as such: MagicDictionary obj = new
33
* MagicDictionary(); obj.buildDict(dictionary); boolean param_2 = obj.search(searchWord);
34
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0