-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortest_unique_prefix.cpp
More file actions
56 lines (52 loc) · 1.16 KB
/
Shortest_unique_prefix.cpp
File metadata and controls
56 lines (52 loc) · 1.16 KB
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
const int SIZE = 26;
struct trie{
trie* child[SIZE];
int frequency;
};
trie* getNode(){
trie* tmp = new trie();
tmp->frequency = 1;
for(int i=0;i<SIZE;i++)
tmp->child[i] = NULL;
return tmp;
}
void insert(trie* root, string key){
trie* tmp = root;
for(int i=0;i<key.length();i++){
int idx = key[i]-'a';
if(!tmp->child[idx])
tmp->child[idx] = getNode();
else
(tmp->child[idx]->frequency)++;
tmp = tmp->child[idx];
}
}
string search(trie* root, string key){
string s = "";
trie* tmp = root;
for(int i=0;i<key.length();i++){
int idx = key[i]-'a';
if(!tmp->child[idx])
return s;
if(tmp->child[idx]->frequency == 1){
s += key[i];
return s;
}
else{
s += key[i];
tmp = tmp->child[idx];
}
}
return s;
}
vector<string> Solution::prefix(vector<string> &A) {
vector<string> res;
trie* root = getNode();
root->frequency = 0;
for(auto word:A)
insert(root,word);
for(auto word:A){
res.push_back(search(root,word));
}
return res;
}