-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prefix_Tree.cpp
54 lines (49 loc) · 1.2 KB
/
Prefix_Tree.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
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Node {
public:
bool is_word;
int count;
vector<Node*> children;
Node() {
is_word = false;
count = 0;
for(int i = 0; i < 26; i ++) {
children.push_back(NULL);
}
}
void insert(string word) {
count ++;
if(word.size() == 0) {
is_word = true;
return;
}
int tmp = word[0]-'a';
if(children[tmp] == NULL) {
children[tmp] = new Node();
}
children[tmp]->insert(word.substr(1));
}
string minPrefix(string word) {
if(word.size() == 0 || count == 1) {
return "";
}
string rst;
rst.push_back(word[0]);
rst += children[word[0]-'a']->minPrefix(word.substr(1));
return rst;
}
};
int main() {
Node* root = new Node();
root->insert("zebra");
root->insert("dog");
root->insert("duck");
root->insert("dot");
cout << root->minPrefix("zebra") << endl;
cout << root->minPrefix("dog") << endl;
cout << root->minPrefix("duck") << endl;
cout << root->minPrefix("dot") << endl;
}