-
Notifications
You must be signed in to change notification settings - Fork 1
/
TrieTree.cpp
85 lines (74 loc) · 1.66 KB
/
TrieTree.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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Trie {
public:
struct TrieNode
{
TrieNode() : val(0), isword(false), next(256, nullptr)
{
}
TrieNode(char value) : val(value), isword(false), next(256, nullptr)
{
}
char val;
bool isword;
vector<TrieNode *> next;
};
typedef struct TrieNode TrieNode;
/** Initialize your data structure here. */
Trie() : m_root(new TrieNode()){
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode * node = m_root;
for (int i = 0; i < word.size(); ++i)
{
if (nullptr == node->next[word[i]])
{
node->next[word[i]] = new TrieNode(word[i]);
}
node = node->next[word[i]];
}
node->isword = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode * node = m_root;
for (int i = 0; i < word.size(); ++i)
{
if (nullptr == node || nullptr == node->next[word[i]])
{
return false;
}
node = node->next[word[i]];
}
return node->isword;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode * node = m_root;
for (int i = 0; i < prefix.size(); ++i)
{
if (nullptr == node || nullptr == node->next[prefix[i]])
{
return false;
}
node = node->next[prefix[i]];
}
return true;
}
private:
TrieNode * m_root;
};
int main()
{
Trie trie;
trie.insert("apple");
cout << trie.search("apple") << endl; // 返回 true
cout << trie.search("app") << endl; // 返回 false
cout << trie.startsWith("app") << endl; // 返回 true
trie.insert("app");
cout << trie.search("app") << endl; // 返回 trues
}