leetcode-676-Implement-Magic-Dictionary

描述


Implement a magic directory with buildDict, and search methods.

For the method buildDict, you’ll be given a list of non-repetitive words to build a dictionary.

For the method search, you’ll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.

Example 1:

1
2
3
4
5
Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False

Note:

  1. You may assume that all the inputs are consist of lowercase letters a-z.
  2. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
  3. Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

分析


题目要求构造一个字典,当单词修改了一个字母,可以判断这个单词在字典中。前缀树的典型应用。

解决方案1(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
class MagicDictionary {
TrieNode root;

public MagicDictionary() {
root = new TrieNode();
}

/** Build a dictionary through a list of words */
public void buildDict(String[] dict) {
for (String s: dict) {
TrieNode node = root;
for (char c: s.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isWord = true;
}
}

/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
public boolean search(String word) {
char[] wordArray = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
for (char c = 'a'; c <= 'z'; c++) {
if (wordArray[i] == c) {
continue;
}
char pre = wordArray[i];
wordArray[i] = c;
if (isWord(new String(wordArray), root)) {
return true;
}
wordArray[i] = pre;
}
}
return false;
}

private boolean isWord(String s, TrieNode root) {
TrieNode node = root;
for (char c: s.toCharArray()) {
if (node.children[c - 'a'] == null) {
return false;
}
node = node.children[c - 'a'];
}
return node.isWord;
}
}

class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
public TrieNode() {};
}

/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* boolean param_2 = obj.search(word);
*/

相关问题


题目来源