[LeetCode]208. Implement Trie (Prefix Tree)
题目描述
思路
实现字典树的插入、搜索和查找过程 详见代码中的注释
代码
#include <iostream>
#include <vector>
using namespace std;
class TrieNode {
public:
char content;
bool isEnd;
int childrenNum;
vector<TrieNode*> children;
TrieNode() : content(
' '), isEnd(
false), childrenNum(
0) {}
TrieNode(
char ch) : content(ch), isEnd(
false), childrenNum(
0) {}
TrieNode* findChild(
char ch) {
if (children.size())
for (
auto p : children)
if (ch == p->content)
return p;
return nullptr;
}
~TrieNode() {
for (
auto child : children)
delete child;
}
};
class Trie {
public:
Trie() {
root =
new TrieNode();
}
~Trie() {
delete root;
}
void insert(
string word) {
if (search(word))
return;
TrieNode* cur = root;
for (
char ch : word) {
TrieNode* child = cur->findChild(ch);
if (child ==
nullptr) {
TrieNode* newNode =
new TrieNode(ch);
cur->children.push_back(newNode);
++cur->childrenNum;
cur = newNode;
}
else {
cur = child;
}
}
cur->isEnd =
true;
}
bool search(
string word) {
TrieNode* cur = root;
for (
char ch : word) {
TrieNode* node = cur->findChild(ch);
if (node ==
nullptr)
return false;
cur = node;
}
return cur->isEnd ==
true;
}
bool startsWith(
string prefix) {
TrieNode* cur = root;
for (
char ch : prefix) {
TrieNode* node = cur->findChild(ch);
if (node ==
nullptr)
return false;
cur = node;
}
return true;
}
private:
TrieNode* root;
};
int main() {
Trie* trie =
new Trie();
trie->insert(
"test");
cout <<
"search(test) " << trie->search(
"test") << endl;
cout <<
"search(tes) " << trie->search(
"tes") << endl;
cout <<
"startWith(tes) " <<trie->startsWith(
"tes") << endl;
system(
"pause");
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-24734.html