题目描述:
实现一个带有buildDict, 以及 search方法的魔法字典。
对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。
对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
示例 1:
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
注意:
你可以假设所有输入都是小写字母 a-z。
为了便于竞赛,测试所用的数据量很小。你可以在竞赛结束后,考虑更高效的算法。
请记住重置MagicDictionary类中声明的类变量,因为静态/类变量会在多个测试用例中保留。 请参阅这里了解更多详情。
依然使用的是前缀树,需要注意的是如果里面有hello和hallo这时候hello就是符合条件的,因此返回true
代码:
class Mytree {
boolean isend;
Mytree child[] = new Mytree[26];
}
class MagicDictionary {
Mytree root;
public MagicDictionary() {
root = new Mytree();
}
public void buildDict(String[] dict) {
for (String string : dict) {
Mytree tree = root;
for (int i = 0; i < string.length(); i++) {
if (tree.child[string.charAt(i) - 'a'] == null) {
tree.child[string.charAt(i) - 'a'] = new Mytree();
}
tree = tree.child[string.charAt(i) - 'a'];
}
tree.isend = true;
}
}
public boolean search(String word) {
Mytree tree = root;
boolean flag = false;
for (int i = 0; i < word.length(); i++) {
if (tree.child[word.charAt(i) - 'a'] == null) {
flag = true;
for (int j = 0; j < 26; j++) {
if (tree.child[j] != null) {
tree = tree.child[j];
if (issearch(word.substring(i + 1), tree)) {
return true;
}
}
}
} else {
tree = tree.child[word.charAt(i) - 'a'];
}
}
tree = root;
for (int i = 0; i < word.length(); i++) {
// 尝试一个个替换一下
char tem = word.charAt(i);
for (int j = 0; j < 25; j++) {
if(tree.child[j] != null && j != tem - 'a'){
if(issearch(word.substring(i + 1), tree.child[j])){
return true;
}
}
}
if(tree.child[tem - 'a'] != null){
tree = tree.child[tem - 'a'];
}else {
return false;
}
}
return false;
}
public boolean issearch(String word, Mytree root) {
for (int i = 0; i < word.length(); i++) {
if(root.child[word.charAt(i) - 'a'] == null){
return false;
}else {
root = root.child[word.charAt(i) - 'a'];
}
}
return root.isend;
}
}