目录
1、实现Trie(前缀树)
struct TrieNode
{
bool isWord;
vector<TrieNode*>children;
TrieNode() : isWord(false), children(26, nullptr) {};
};
class Trie {
private:
TrieNode* TrieHead;
public:
TrieNode *find(string str)
{
TrieNode* ptr = TrieHead;
for (auto ch : str)
{
if (ptr->children[ch - 'a'] == nullptr)
return nullptr;
ptr = ptr->children[ch - 'a'];
}
return ptr;
}
Trie()
{
TrieHead = new TrieNode();
}
void insert(string word)
{
TrieNode* ptr = TrieHead;
for (auto ch : word)
{
if (ptr->children[ch - 'a'] == nullptr)
{
ptr->children[ch - 'a'] = new TrieNode();
}
ptr = ptr->children[ch - 'a'];
}
ptr->isWord = true;
}
bool search(string word)
{
TrieNode *ptr = find(word);
if(ptr != nullptr)
return ptr->isWord;
return false;
}
bool startsWith(string prefix)
{
return find(prefix);
}
};
2、单词替换
思路:用所有的词根构造成一颗前缀树,每个前缀树节点包括26个子孩子和是否以该节点结尾构成单词。
//定义节点
struct TrieNode
{
bool isWord;
vector<TrieNode*>children;
TrieNode() : isWord(false), children(26, nullptr) {};
};
class Solution {
private:
TrieNode* TrieHead;
public:
Solution()
{
TrieHead = new TrieNode();
}
~Solution()
{
delete TrieHead;
}
//插入词根
void insert(string str)
{
TrieNode* ptr = TrieHead;
for (auto ch : str)
{
if (ptr->children[ch - 'a'] == nullptr)
{
ptr->children[ch - 'a'] = new TrieNode();
}
ptr = ptr->children[ch - 'a'];
}
ptr->isWord = true;
}
string replaceWords(vector<string>& dict, string sentence)
{
//插入所有词根
for (auto str : dict)
{
insert(str);
}
vector<string>strs;
int i = 0;
while (i < sentence.size())
{
int j = i;
string word = "";
//提取单词
for (; j < sentence.size() && sentence[j] != ' '; j++)
{
word += sentence[j];
}
TrieNode* ptr = TrieHead;
string cigen = "";//词根
int flag = 0; //0代表为放入标志
for (auto ch : word)
{
if (ptr->children[ch - 'a'] == nullptr) //未找到词根
{
flag = 1;
strs.push_back(word);
break;
}
else
{
ptr = ptr->children[ch - 'a'];
cigen += ch;
if (ptr->isWord) //保证最短词根【注意:可能只是word只是词根的前缀】
{
flag = 1;
strs.push_back(cigen);
break;
}
}
}
if (!flag)
{
strs.push_back(word);
}
i = j + 1;
}
string res;
for (auto str : strs)
{
res += str + ' ';
}
return res.substr(0, res.size() - 1);
}
};