-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathLongest.cpp
92 lines (81 loc) · 1.93 KB
/
Longest.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
class TrieNode{
public:
char data;
TrieNode** children;
bool isTerminal;
TrieNode(char data){
this->data = data;
children = new TrieNode*[26];
for(int i=0;i<26;i++){
children[i] = NULL;
}
isTerminal = false;
}
};
class Trie{
TrieNode* root;
public:
Trie(){
root = new TrieNode('\0');
}
//Insert
void insert(TrieNode* root, string word){
//Base Case
if(word.size()==0){
root->isTerminal = true;
return;
}
int index = word[0]-'a';
TrieNode* child;
if(root->children[index]){
child = root->children[index];
}
else{
child = new TrieNode(word[0]);
root->children[index] = child;
}
insert(child, word.substr(1));
}
void insert(string word){
insert(root, word);
}
//Search Prefix
bool search(TrieNode* root, string word){
if(word.size() == 0){
//cout<<"x";
return root->isTerminal;
}
int index = word[0] - 'a';
if(root->children[index] != NULL && root->children[index]->isTerminal){
return search(root->children[index], word.substr(1));
}
else{
return false;
}
}
bool search(string word){
return search(root, word);
}
};
string completeString(int n, vector<string> &a){
// Write your code here.
Trie dummy;
for(auto it : a){
dummy.insert(it);
}
int len = 0;
string ans;
for(int i=0;i<n;i++){
if(dummy.search(a[i])){
if(a[i].length() > len){
len = a[i].length();
ans = a[i];
}
else if(a[i].length() == len){
ans = min(ans, a[i]);
}
}
}
if(ans.size()==0)ans="None";
return ans;
}