-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqianZhuiShu.cpp
65 lines (56 loc) · 1.06 KB
/
qianZhuiShu.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
#include<string>
#include<unordered_map>
using namespace std;
class trienode
{
public:
trienode() : isWord(false) {};
unordered_map<char, trienode*> children;
bool isWord;
};
class Trie
{
public:
Trie()
{
root = new trienode();// void head
};
void insert(string s)
{
if (s.size() <= 0) return;
trienode* node = root;
for (int i = 0; i < s.length(); i++)
{
if (node->children.find(s[i])==node->children.end())
{
node->children[s[i]]= new trienode();
}
node = node->children[s[i]];
}
node->isWord = true;
}
bool search(string word)
{
return retrive(word, true);
}
bool isprefix(string word)
{
return retrive(word, false);
}
private:
inline bool retrive(const string& key, bool isword)
{
if (key.size() <= 0) return;
trienode* node = root;
for (int i = 0; i < key.length(); i++)
{
if (node->children.find(key[i]) == node->children.end())
{
return false;
}
node = node->children[key[i]];
}
return isword?node->isWord:true;//e.g here is ¡®input¡¯in dic but search 'in'.
}
trienode* root;
};