标签:ali else 题目 prefix iat eof 题意 problems param
题意:实现一个前缀树
class Trie {
public:
int map[100005][126];
int tag[100005][126];
int num;
/** Initialize your data structure here. */
Trie() {
memset(map,0,sizeof(map));
memset(tag,0,sizeof(tag));
num=0;
}
/** Inserts a word into the trie. */
void insert(string word) {
Add(word,0,0);
}
void Add(string word,int i,int pos)
{
if(i==word.length())
{
return;
}
if(map[pos][word[i]]==0)
{
map[pos][word[i]]=++num;
}
if(i==word.length()-1)
{
tag[pos][word[i]]=1;
}
Add(word,i+1,map[pos][word[i]]);
}
/** Returns if the word is in the trie. */
bool search(string word) {
return SearchWord(word,0,0,1);
}
bool SearchWord(string word,int i,int pos,int t)
{
if(i==word.length())
return false;
if(map[pos][word[i]]==0)
{
return false;
}
else
{
if(i==word.length()-1)
{
if(t==1&&tag[pos][word[i]]==1)
return true;
if(t==0)
return true;
}
return SearchWord(word,i+1,map[pos][word[i]],t);
}
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return SearchWord(prefix,0,0,0);
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
LeetCode 208. Implement Trie (Prefix Tree)
标签:ali else 题目 prefix iat eof 题意 problems param
原文地址:https://www.cnblogs.com/dacc123/p/12306348.html