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:
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:
- You may assume that all the inputs are consist of lowercase letters a-z.
- For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
- 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.
Approach
- 题目大意实现类的方法,里面唯一难的地方应该就是search()方法实现,这里我是用深搜实现的,我的思路是用flag做标记,flag为true说明已经有字母用了移形换影,false说明还没用这技能,那么我每深搜一个字母的时候,我就判断flag,假如flag为true,那么已经用过这技能,那么我只能沿这个字母往下搜,假如flag为false,那么技能还没使用,我可以选择用,也可以选择不用,然后继续往下搜,递归边界就是当搜到最后一个字母的时候,也是根据flag做相应的判断,看代码思路会更加清晰。
Code
struct Trie
{
Trie* letter[26];
bool isword;
Trie() {
isword = false;
for (int i = 0; i < 26; i++) {
letter[i] = nullptr;
}
}
};
class MagicDictionary {
public:
Trie* root;
/** Initialize your data structure here. */
MagicDictionary() {
root = new Trie();
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for (string &d : dict) {
Trie *head = root;
for (char &w : d) {
int c = w - 'a';
if (!head->letter[c]) {
head->letter[c] = new Trie();
}
head = head->letter[c];
}
head->isword = true;
}
}
bool Search_str(string &word, int n, Trie *head, int pos, bool flag) {
int c = word[pos] - 'a';
if (pos == n) {
if (flag) {
return head&&head->letter[c] && head->letter[c]->isword;
}
else {
for (int i = 0; i < 26; i++) {
if (!head->letter[i] || c == i)continue;
if (head->letter[i]->isword)return true;
}
return false;
}
}
if (flag) {
return head&&head->letter[c] && Search_str(word, n, head->letter[c], pos + 1, flag);
}
else {
for (int i = 0; i < 26; i++) {
if (head->letter[i] || c == i)continue;
if (Search_str(word, n, head->letter[i], pos + 1, true)) {
return true;
}
}
return head&&head->letter[c] && Search_str(word, n, head->letter[c], pos + 1, false);
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
return Search_str(word, word.size() - 1, root, 0, false);
}
};