前缀树问题,力扣208,211,648,677
class Node {
public:
char val;
int value;
bool isend;
vector<Node*>next;
Node() :value(0),isend(false){
next.resize(26);
}
};
class Trie {
public:
Node* root;
unordered_map<string, int> cnt;
Trie() {
root = new Node();//建立一个为空的根节点
}
//插入字符
void insert(string word) {
Node* curr = root;
for (int i = 0; i<word.size(); i++)
{
char c = word[i];
//插入节点,先看看当前的node是否已经有指向该字母的next指针
//如果没有,就新建一个指针
if (curr->next[c - 'a'] == NULL) {
curr->next[c - 'a'] = new Node();
}
//无论是新建还是原本存在,curr移动到该位置
curr = curr->next[c - 'a'];
curr->val = c;//这一步若是新建则为其赋值,不是新建赋值也无伤大雅
if (i == word.size() - 1)
{
curr->isend = true;
}
}
}
//当该节点为前缀节点时,节点的value累加
void insert(string key, int num)
{
int delta = num;
if (cnt.count(key))
{
delta -= cnt[key];
}
cnt[key] = num;
Node* cur = root;
for (auto c : key) {
if (cur->next[c - 'a'] == nullptr) {
cur->next[c - 'a'] = new Node();
}
cur = cur->next[c - 'a'];
cur->value += delta;
}
}
//查找word是否在前缀树之中
bool search_total(string word) {
Node* curr = root;
for (int i = 0; i<word.size(); i++)
{
char c = word[i];
//插入节点,先看看当前的node是否已经有指向该字母的next指针
//如果没有,就新建一个指针
if (curr->next[c - 'a'] == NULL) {
return false;
}
curr = curr->next[c - 'a'];
if (i == word.size() - 1 )
{
return curr->isend;
}
}
return true;
}
//判断word是否在前缀树中,包括“.××”类型
bool search_pattern(string word) {
return dfs(word, 0, root);
}
bool dfs(string& word, int index, Node* curr)//深度遍历
{
if (index == word.size())
{
return curr->isend;
}
char ch = word[index];
if (ch >= 'a' && ch <= 'z') {
Node * child = curr->next[ch - 'a'];
if (child != nullptr && dfs(word, index + 1, child)) {
return true;
}
}
else if (ch == '.')
{
for (int i = 0; i<26; i++)
{
Node * child = curr->next[i];
if (child != nullptr && dfs(word, index + 1, child)) {
return true;
}
}
}
return false;
}
//判断前缀prefix是否在前缀树中
bool startsWith(string prefix) {
Node* curr = root;
for (int i = 0; i<prefix.size(); i++)
{
char c = prefix[i];
if (curr->next[c - 'a'] == NULL) {
return false;
}
curr = curr->next[c - 'a'];
}
return true;
}
//单词替换,当单词存在前缀树中的前缀时,改为前缀单词
string hasstartsWith(string word) {
Node* curr = root;
for (int i = 0; i<word.size(); i++)
{
char c = word[i];
curr = curr->next[c - 'a'];
if (curr!=nullptr&&curr->isend)
{
return word.substr(0, i + 1);
}
if (curr == NULL)
{
return word;
}
}
return word;
}
};