class TrieNode{
public:
vector<TrieNode*> nodes;
bool tag=0;
TrieNode():nodes(26,nullptr){}
void insert(string & word){
TrieNode *cur=this;
for(auto ch:word){
int idx=ch-'a';
if(cur->nodes[idx]==nullptr) cur->nodes[idx]=new TrieNode();
cur=cur->nodes[idx];
}
cur->tag=1;
}
string _replaceWords(string & word){
string res;
TrieNode *cur=this;
for(auto ch:word){
int idx=ch-'a';
if(cur->nodes[idx]==nullptr) break;
res+=ch;
cur=cur->nodes[idx];
if(cur->tag==1) return res;
}
return word;
}
};
class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
TrieNode * root=new TrieNode();
for(auto &dic:dictionary) root->insert(dic);
string res="";
string tmp="";
for(auto s:sentence){
if(s==' '){
res+=root->_replaceWords(tmp);
res+=" ";
tmp="";
continue;
}else tmp+=s;
}
return res+=root->_replaceWords(tmp);
}
};
leetcode 648单词 替换(字典树中等)
最新推荐文章于 2023-04-05 16:13:58 发布