题目链接
题目描述
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary() 初始化对象
void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。
示例:
输入
[“MagicDictionary”, “buildDict”, “search”, “search”, “search”, “search”]
[[], [[“hello”, “leetcode”]], [“hello”], [“hhllo”], [“hell”], [“leetcoded”]]
输出
[null, null, false, true, false, false]
解释
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict([“hello”, “leetcode”]);
magicDictionary.search(“hello”); // 返回 False
magicDictionary.search(“hhllo”); // 将第二个 ‘h’ 替换为 ‘e’ 可以匹配 “hello” ,所以返回 True
magicDictionary.search(“hell”); // 返回 False
magicDictionary.search(“leetcoded”); // 返回 False
提示:
1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
dictionary[i] 仅由小写英文字母组成
dictionary 中的所有字符串 互不相同
1 <= searchWord.length <= 100
searchWord 仅由小写英文字母组成
buildDict 仅在 search 之前调用一次
最多调用 100 次 search
求解思路1
- 暴力查找:遍历字典中每一个单词,找到符合条件的返回
true
,如果没有找到则返回false
。
实现代码1
class MagicDictionary {
private String[] words;
public MagicDictionary() {
}
public void buildDict(String[] dictionary) {
this.words = dictionary;
}
public boolean search(String searchWord) {
for (int i = 0; i < words.length; i ++) {
if (searchWord.length() == words[i].length()) {
int t = -1;
for (int j = 0; j < searchWord.length(); j ++) {
if (searchWord.charAt(j) != words[i].charAt(j)) t++;
}
if (t == 0) return true;
}
}
return false;
}
}
求解思路2
- 构建字典树:创建一个Tree类,每个结点存放一个字符,用一个
boolean
变量来表示单词是否到达结尾。 - 在查找过程中,通过深搜递归,
pos
表示当前递归的层数(即单词到达了第几个字母)。因为需要有一个字母不同,因此flag
的值需要我们手动做一下改变:如果遇到不相同的字母,遍历其他25个字母查找是否有符合条件的继续递归,并把flag
改为true
。
实现代码2
class Tree {
boolean isFinish;
Tree[] child;
public Tree() {
isFinish = false;
child = new Tree[26];
}
}
class MagicDictionary {
Tree root;
public MagicDictionary() {
root = new Tree();
}
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
Tree cur = root;
for (int i = 0; i < word.length(); i ++) {
int index = word.charAt(i) - 'a';
if (cur.child[index] == null) {
cur.child[index] = new Tree();
}
cur = cur.child[index];
}
cur.isFinish = true;
}
}
public boolean search(String searchWord) {
return dfs(searchWord, root, 0, false);
}
private boolean dfs(String searchWord, Tree node, int pos, boolean flag) {
if (pos == searchWord.length()) {
return flag && node.isFinish;
}
int index = searchWord.charAt(pos) - 'a';
if (node.child[index] != null) {
if (dfs(searchWord, node.child[index], pos + 1, flag)) {
return true;
}
}
if (!flag) {
for (int i = 0; i < 26; i ++) {
if (i != index && node.child[i] != null) {
if (dfs(searchWord, node.child[i], pos + 1, true)) {
return true;
}
}
}
}
return false;
}
}