-
Notifications
You must be signed in to change notification settings - Fork 7
/
208.cpp
78 lines (68 loc) · 1.99 KB
/
208.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
class TrieNode{
public:
TrieNode(){
memset(next,0,sizeof(next));
word = false;
}
bool containChar(char c){return next[c - 'a'] == NULL ? false : true;}
void putNext(char c,TrieNode *nd){next[c - 'a'] = nd;}
TrieNode* getNext(char c) {return next[c - 'a'];}
bool isWord() {return word;}
void setWord() {word = true;}
private:
bool word;//从根节点到当前节点的所有字符组成的单词是否包含在字典中
TrieNode* next[26];
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *curr = root;
for(char c : word){
if(curr->containChar(c)) curr = curr->getNext(c);
else{
TrieNode *newNode = new TrieNode();
curr->putNext(c,newNode);
curr = newNode;
}
}
curr->setWord();
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *curr = root;
int len = 0;
for(char c : word){
if(!curr->containChar(c)) break;
else curr = curr->getNext(c);
len++;
}
if(len != word.size()) return false;
return curr->isWord();
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *curr = root;
int len = 0;
for(char c : prefix){
if(!curr->containChar(c)) break;
else curr = curr->getNext(c);
len++;
}
if(len != prefix.size()) return false;
return true;
}
private:
TrieNode *root;
};
/**
* 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);
*/