此文件为纯手撸.h文件,引用后调用相应的接口即可。
#pragma once
/* 前缀树(字典树)*/
#include <iostream>
using namespace std;
class TrieNode
{
public:
int path;//当前字母被经过的次数
int end;//当前单词出现的次数
TrieNode *next[26];
TrieNode()
{
path = 0;
end = 0;
for (int i = 0; i < 26; i++)
{
next[i] = NULL;
}
}
};
class Trie
{
public:
TrieNode *root;
Trie()
{
root = new TrieNode();
}
void insertWord(string word)
{
TrieNode *p = root;
for (int i = 0; i < word.size(); i++)
{
if (p->next[word[i]-'a'] == NULL)
{
p->next[word[i] - 'a'] = new TrieNode;
}
p = p->next[word[i] - 'a'];
p->path++;
}
p->end++;
}
int searchWord(string word)
{
TrieNode *p = root;
for (int i = 0; i < word.size(); i++)
{
if (p->next[word[i]-'a'] == NULL)
{
return 0;
}
p = p->next[word[i] - 'a'];
}
if (p->end!=0)
{
return p->end;
}
else
{
return 0;
}
}
void deleteWord(string word)
{
TrieNode *p = root;
if (searchWord(word))
{
for (int i = 0; i < word.size(); i++)
{
if (--p->next[word[i]-'a']->path == 0)
{
p->next[word[i] - 'a'] = NULL;
return;
}
p = p->next[word[i] - 'a'];
}
p->end--;
}
}
int perfixNumber(string word)
{
TrieNode *p = root;
for (int i = 0; i < word.size(); i++)
{
if (--p->next[word[i] - 'a']->path == 0)
{
p->next[word[i] - 'a'] = NULL;
return 0;
}
p = p->next[word[i] - 'a'];
}
return p->path;
}
private:
};
/* main for test */
/*
#include "trieTree.h"
#include <iostream>
using namespace std;
int main()
{
Trie *trie = new Trie();
cout << trie->searchWord("zuo") << endl;
trie->insertWord("zuo");
cout << trie->searchWord("zuo") << endl;
trie->deleteWord("zuo");
cout << trie->searchWord("zuo") << endl;
trie->insertWord("zuo");
trie->insertWord("zuo");
trie->deleteWord("zuo");
cout << trie->searchWord("zuo") << endl;
trie->insertWord("zuoa");
trie->insertWord("zuoac");
trie->insertWord("zuoab");
trie->insertWord("zuoad");
trie->insertWord("zuoa");
cout << trie->searchWord("zuoa") << endl;
cout << trie->perfixNumber("zuo") << endl;
system("pause");
return 0;
}
*/