-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_ShortestUniquePrefixForEveryWord.cpp
68 lines (63 loc) · 1.35 KB
/
GFG_ShortestUniquePrefixForEveryWord.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
/*
Shortest Unique prefix for every word
https://practice.geeksforgeeks.org/problems/shortest-unique-prefix-for-every-word/0
*/
class Trie{
struct TrieNode{
TrieNode* children[26];
int cnt=0;
bool isEnd;
};
TrieNode *root;
public:
Trie() {
root = new TrieNode();
}
void insert(string& word)
{
TrieNode* ptr = root;
int key=0;
for(char &c: word)
{
key = c-'a';
if(ptr->children[key] == nullptr)
ptr->children[key] = new TrieNode();
ptr = ptr->children[key];
ptr->cnt++;
}
root->isEnd = true;
}
string searchPrefix(string& word)
{
TrieNode *ptr = root;
int key=0;
string pre="";
for(char &c: word)
{
pre+=c;
key = c-'a';
ptr = ptr->children[key];
if(ptr->cnt == 1)
return pre;
}
return (pre);
}// end search
};
class Solution
{
public:
vector<string> findPrefixes(string arr[], int n)
{
Trie tr;
for(int i=0; i<n; i++)
{
tr.insert(arr[i]);
}
vector<string> ans(n);
for(int i=0; i<n; i++)
{
ans[i] = tr.searchPrefix(arr[i]);
}
return ans;
}//
};