放码过来
#include <iostream>
#include <string>
using namespace std;
struct TrieNode
{
char data;
TrieNode *children[26];
bool isEndingChar;
TrieNode(char data): data(data), isEndingChar(false)
{
for (int i = 0; i < 26; ++i)
children[i] = nullptr;
}
};
class Trie
{
private:
TrieNode *root = new TrieNode('/');
public:
void insert(string str)
{
TrieNode *p = root;
for (int i = 0; i < str.size(); ++i)
{
int index = str[i] - 'a';
if (p->children[index] == nullptr)
{
TrieNode *newNode = new TrieNode(str[i]);
p->children[index] = newNode;
}
p = p->children[index];
}
p->isEndingChar = true;
}
bool find(string str)
{
TrieNode *p = root;
for (int i = 0; i < str.size(); ++i)
{
int index = str[i] - 'a';
if (p->children[index] == nullptr)
return false;
p = p->children[index];
}
if (p->isEndingChar == false)
return false;
else
return true;
}
};
int main()
{
Trie myTrie;
myTrie.insert("hello");
myTrie.insert("tlq");
myTrie.insert("xsq");
if (myTrie.find("hello"))
{
cout << "myTrie has string of [hello]" << endl;
}
if (myTrie.find("tlq"))
{
cout << "myTrie has string of [tlq]" << endl;
}
if (myTrie.find("xsq"))
{
cout << "myTrie has string of [xsq]" << endl;
}
if (myTrie.find("balabala"))
{
cout << "myTrie has string of [hello]" << endl;
}
else
{
cout << "myTrie don't have string of [balabala]" << endl;
}
return 0;
}