LeetCode 676. 实现一个魔法字典
思路
首先创建字典树,之后对字典树进行dfs搜索。
代码实现
1 class Trie { 2 public: 3 bool isWord; 4 Trie* next[26]; 5 6 void insert(const string word) { 7 Trie* t = this; 8 for(int i = 0; i < word.length(); ++i) { 9 if(t->next[word[i]-'a'] == NULL) 10 t->next[word[i]-'a'] = new Trie(); 11 t = t->next[word[i]-'a']; 12 } 13 14 t->isWord = true; 15 } 16 }; 17 18 19 class MagicDictionary { 20 private: 21 Trie* t; 22 public: 23 /** Initialize your data structure here. */ 24 MagicDictionary() { 25 t = new Trie(); 26 } 27 28 void buildDict(vector<string> dictionary) { 29 for(const string &word: dictionary) { 30 t->insert(word); 31 } 32 } 33 34 bool search(string searchWord) { 35 return dfs(t, searchWord, 0, false); 36 } 37 38 //isMod为true时,表示已经替换了一个字母 39 bool dfs(Trie* t, const string& word, int index, bool isMod) { 40 if(t == NULL) 41 return false; 42 if(index > word.length()) 43 return false; 44 if(index == word.length() ) 45 return t->isWord && isMod; 46 47 for(int i = 0; i < 26; ++i) { 48 if(t->next[i] != NULL) { 49 if(i == word[index]-'a') { 50 //注意这里不能直接 return dfs(t->next[i], word, index+1, isMod); 51 //这样直接return dfs会导致无法搜索到后续的for循环的情况 52 if(dfs(t->next[i], word, index+1, isMod)) 53 return true; 54 }else { 55 if(!isMod && dfs(t->next[i], word, index+1, true)) 56 return true; 57 } 58 } 59 } 60 61 return false; 62 } 63 }; 64 65 /** 66 * Your MagicDictionary object will be instantiated and called as such: 67 * MagicDictionary* obj = new MagicDictionary(); 68 * obj->buildDict(dictionary); 69 * bool param_2 = obj->search(searchWord); 70 */