class Solution {
public:
typedef struct trie_node{
int count;
struct trie_node* next[26];
bool exist;
}TrieNode , *Trie;
TrieNode* CreatTrieNode()
{
TrieNode* root=new TrieNode();
root->count=0;
memset(root->next, 0, sizeof(root->next));
root->exist=false;
return root;
}
void insert(TrieNode* root,char *word)
{
TrieNode* Node=root;
while(*word)
{
//cout<<*word<<endl;
char c=*word;
int id=c-'a';
if(Node->next[id]==NULL)
Node->next[id]=CreatTrieNode();
Node=Node->next[id];
Node->count++;
word++;
}
Node->exist=true;
}
string find_word(TrieNode* root,string word)
{
TrieNode* node=root;
for(int i=0;i<=word.size()-1;i++)
{
int id=word[i]-'a';
//cout<<word[i];
if(node->exist==true)
return word.substr(0,i);
if(node->next[id]==NULL)
break;
node=node->next[id];
}
return word;
}
string replaceWords(vector<string>& dict, string sentence) {
TrieNode* root = CreatTrieNode();
for(string a:dict)
{
char *p=(char*)a.data();
insert(root, p);
}
string res="";
istringstream is(sentence);
string n;
while(is>>n)
{
if(!res.empty()) res+=' ';
res+=find_word(root, n);
}
return res;
}
};
本文介绍了一种使用字典树(Trie)的数据结构来高效地查找并替换句子中的单词前缀。通过构建字典树,可以在O(m)的时间复杂度内完成单词的插入操作,并能在O(n)的时间复杂度内完成对整个句子中单词的查找和替换,其中m为单词长度,n为句子长度。文章详细解释了字典树节点的设计、单词的插入流程以及查找替换的具体实现。

被折叠的 条评论
为什么被折叠?



