LeetCode Add and Search Word - Data structure design (trie树)
2015-05-18 13:16
615 查看
class WordDictionary { public: WordDictionary(){ tree=create(); } void addWord(string word) { node *tmp=tree; node *p=0; //负责创建结点 for(int i=0; i<word.size(); i++) { if(!tmp->next[word[i]-'a']) //没有这个分支,创建它 { p=create(); tmp->next[word[i]-'a']=p; } tmp=tmp->next[word[i]-'a']; //往下走 } tmp->tag=1; } bool search(string word) { if(DFS(tree,word.c_str())==true)//搜 return true; return false; } private: struct node { bool tag; node *next[26]; }; node *tree;//先建立树根 node *create() { node *tmp=new(node); tmp->tag=0; for(int i=0; i<26; i++) tmp->next[i]=0; return tmp; } bool DFS(node *t,const char *p) { if(*(p+1)=='\0') { if(*p=='.') //'.'刚好是最后一个 { for(int i=0; i<26; i++) if(t->next[i]&&t->next[i]->tag==1) return true; return false; //无匹配 } if(t->next[*p-'a'] && t->next[*p-'a']->tag==1) return 1; return false; } if(*p=='.')//要搜索全部 { for(int i=0; i<26; i++) if( t->next[i] && DFS(t->next[i],p+1) ) return true; return false; } if( t->next[*p-'a'] && DFS(t->next[*p-'a'],p+1)) return true; return false; } }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
AC代码
相关文章推荐
- LeetCode 211.Add and Search Word - Data structure design(trie树)
- leetcode---Add and Search Word - Data structure design---Trie树
- 211.leetcode Add and Search Word - Data structure design(medium)[Trie树]
- Add and Search Word - Data structure design -- leetcode
- Leetcode 211. Add and Search Word - Data structure design
- LeetCode 211. Add and Search Word - Data structure design
- [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
- leetcode 日经贴,Cpp code -Add and Search Word - Data structure design
- 【Leetcode】Add and Search Word - Data structure design
- [leetcode] Add and Search Word - Data structure design
- Leetcode 211. Add and Search Word - Data structure design
- LeetCode 211 Add and Search Word - Data structure design
- LeetCode Add and Search Word - Data structure design
- [leetcode] 211. Add and Search Word - Data structure design 解题报告
- LeetCode211:Add and Search Word - Data structure design
- LeetCode211:Add and Search Word - Data structure design
- [Leetcode]Add and Search Word - Data structure design
- Leetcode: Add and Search Word - Data structure design
- 《leetCode》:Add and Search Word - Data structure design
- 【LeetCode】211. Add and Search Word - Data structure design