您的位置:首页 > 其它

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代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: