-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortestUniquePrefix.cpp
More file actions
61 lines (42 loc) · 1.1 KB
/
shortestUniquePrefix.cpp
File metadata and controls
61 lines (42 loc) · 1.1 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
57
58
59
60
61
#include <bits/stdc++.h>
using namespace std;
struct node{
node* next[26];
int end;
node(){
end = 0;
for(int i = 0; i < 26; ++i) next[i] = NULL;
}
};
class Trie{
public:
node *root;
Trie(){ root = new node();}
void insert(string word){
node* cur = root;
for(auto c : word){
if(cur->next[c-'a'] == NULL) cur->next[c-'a'] = new node();
cur = cur->next[c-'a'];
cur->end++;
}
return;
}
string get_pre(string word){
node* cur = root;
string pre = "";
for(auto c : word){
cur = cur->next[c-'a'];
pre += c;
if(cur->end == 1) return pre;
//return if only one word(current) was seen upto this sequence of characters
}
return pre;
}
};
vector<string> prefix(vector<string> &a) {
Trie* t = new Trie();
vector<string> sup; //shortest unique prefix for each word
for(auto word : a) t->insert(word);
for(auto word : a) sup.push_back(t->get_pre(word));
return sup;
}