-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path208.实现-trie-前缀树.cpp
91 lines (86 loc) · 1.93 KB
/
208.实现-trie-前缀树.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* @lc app=leetcode.cn id=208 lang=cpp
*
* [208] 实现 Trie (前缀树)
*/
#include "a_header.h"
// @lc code=start
class Trie
{
private:
struct TrieNode
{
bool isWord;
unordered_map<char, TrieNode *> children;
TrieNode()
{
isWord = false;
}
TrieNode(bool isw)
{
isWord = isw;
}
};
TrieNode *root;
public:
Trie()
{
root = new TrieNode();
}
void insert(string word)
{
TrieNode *node = root;
for (size_t i = 0; i < word.length(); i++)
{
if (node->children.find(word[i]) == node->children.end())
{
node->children[word[i]] = new TrieNode(i == word.length() - 1);
}
else if (i == word.length() - 1)
{
node->children[word[i]]->isWord = true;
}
node = node->children[word[i]];
}
}
bool search(string word)
{
TrieNode *node = root;
for (size_t i = 0; i < word.length(); i++)
{
if (node->children.find(word[i]) == node->children.end())
{
return false;
}
else
{
node = node->children[word[i]];
}
}
return node->isWord;
}
bool startsWith(string prefix)
{
TrieNode *node = root;
for (size_t i = 0; i < prefix.length(); i++)
{
if (node->children.find(prefix[i]) == node->children.end())
{
return false;
}
else
{
node = node->children[prefix[i]];
}
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
// @lc code=end