-
Notifications
You must be signed in to change notification settings - Fork 0
/
ShortestUniquePrefix.cpp
110 lines (91 loc) · 2.24 KB
/
ShortestUniquePrefix.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// { Driver Code Starts
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
struct Node {
Node *arr[26];
bool flag = false;
int count = 0;
bool contains(char ch) {
return (arr[ch - 'a'] != nullptr);
}
void put(char ch, Node *newNode) {
newNode->count = 1;
arr[ch - 'a'] = newNode;
}
Node *getNext(char ch) {
return arr[ch - 'a'];
}
void setFlag() {
flag = true;
}
bool isFlagSet() {
return flag;
}
};
void insert(Node *root, string word) {
Node *temp = root;
for (char ch : word) {
if (!temp->contains(ch)) {
Node *newNode = new Node();
temp->put(ch, newNode);
temp = temp->getNext(ch);
} else {
temp = temp->getNext(ch);
temp->count++;
}
}
temp->setFlag();
}
void shortestPrefix(Node *root, string word, vector<string> &ans) {
string temp;
for (char ch : word) {
temp += ch;
// cout << ch << " 555 " << temp << " 666 " << root->count << endl;
root = root->getNext(ch);
if (root->count == 1) {
ans.push_back(temp);
return;
}
}
ans.push_back(temp);
}
vector<string> findPrefixes(string arr[], int n)
{
Node *root = new Node();
for (int i = 0; i < n; i++) {
insert(root, arr[i]);
}
vector<string> ans;
for (int i = 0; i < n; i++) {
shortestPrefix(root, arr[i], ans);
}
return ans;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
string arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
Solution ob;
vector<string> ans = ob.findPrefixes(arr, n);
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
cout << "\n";
}
return 0;
}
// } Driver Code Ends