leetcode676 实现一个魔法字典
作者:互联网
思路:
字典树。
实现:
1 class TrieNode{ 2 public: 3 vector<TrieNode*>v; 4 bool isLeaf=false; 5 TrieNode(){ 6 v.resize(26,NULL); 7 } 8 }; 9 class Trie{ 10 public: 11 TrieNode*root; 12 Trie(){ 13 root=new TrieNode(); 14 } 15 void insert(string&s){ 16 int n=s.length(); 17 auto cur=root; 18 for(int i=0;i<n;i++){ 19 int id=s[i]-'a'; 20 if(cur->v[id]==NULL){ 21 cur->v[id]=new TrieNode(); 22 } 23 cur=cur->v[id]; 24 } 25 cur->isLeaf=true; 26 } 27 bool search(string&s){ 28 return _search(s,0,root,false); 29 30 } 31 bool _search(string&s,int p,TrieNode*root,bool isReplaced){ 32 int n=s.length(); 33 if(p==n-1){ 34 int id=s[p]-'a'; 35 for(int i=0;i<26;i++){ 36 if(root->v[i]==NULL){ 37 continue; 38 } 39 else if(i==id){ 40 if(isReplaced and root->v[i]->isLeaf){ 41 return true; 42 } 43 } 44 else{ 45 if(!isReplaced and root->v[i]->isLeaf){ 46 return true; 47 } 48 } 49 } 50 return false; 51 } 52 int id=s[p]-'a'; 53 for(int i=0;i<26;i++){ 54 if(root->v[i]==NULL){ 55 continue; 56 } 57 else if(i==id){ 58 if(_search(s,p+1,root->v[i],isReplaced)){ 59 return true; 60 } 61 } 62 else{ 63 64 if(!isReplaced and _search(s,p+1,root->v[i],true)){ 65 return true; 66 } 67 } 68 } 69 return false; 70 } 71 72 }; 73 class MagicDictionary { 74 public: 75 Trie*root=new Trie(); 76 MagicDictionary() { 77 78 } 79 80 void buildDict(vector<string> dictionary) { 81 int n=dictionary.size(); 82 for(int i=0;i<n;i++){ 83 root->insert(dictionary[i]); 84 } 85 86 } 87 88 bool search(string searchWord) { 89 return root->search(searchWord); 90 91 } 92 };
标签:search,return,int,true,魔法,leetcode676,root,id,字典 来源: https://www.cnblogs.com/wangyiming/p/16467187.html