给一个字典,然后给定一个字符串,求字典中所有以该字符串为前缀的单词。会有多次查询,要求通过预处理建立一个查询结构。
可假设字典仅含有小写字母。
struct Node
{
bool isTail;
Node *child[26];
Node()
{
isTail = false;
for(int i = 0; i < 26; ++i)
child[i] = NULL;
}
};
Node *ROOT;
void addWord(string &word)
{
Node *cur = ROOT;
for(int i = 0; i < word.size(); ++i)
{
char ch = word[i];
if(cur->child[ch - 'a'] == NULL)
cur->child[ch - 'a'] = new Node();
cur = cur->child[ch - 'a'];
}
cur->isTail = true;
}
void BuildTree(vector<string> &words)
{
ROOT = new Node();
for(vector<string>::size_type i = 0; i != words.size(); ++i)
addWord(words[i]);
}
Node *SearchNode(string &prefix)
{
Node *ret = ROOT;
for(string::size_type i = 0; i != prefix.size(); ++i)
if(NULL == ret->child[prefix[i] - 'a'])
return NULL;
else
ret = ret->child[prefix[i] - 'a'];
return ret;
}
void dfs(Node *start, vector<string> &ret, string prefix)
{
if(start->isTail)
ret.push_back(prefix);
for(int i = 0; i < 26; ++i)
if(NULL != start->child[i])
{
prefix.push_back((char)('a' + i));
dfs(start->child[i], ret, prefix);
}
}
vector<string> getWords(string &prefix)
{
Node *start = SearchNode(prefix);
vector<string> ret;
if(NULL == start)
return ret;
dfs(start, ret, prefix);
return ret;
}
int main()
{
vector<string> words;
words.push_back("abcsdfa");
words.push_back("sdfwsd");
words.push_back("abcsdrfw");
words.push_back("fafse");
BuildTree(words);
string prefix("abc");
vector<string> res = getWords(prefix);
return 0;
}