Shortest Unique prefix for every word | Using Trie |GFG Problem of the Day 04-02-2022

preview_player
Показать описание
Here I am explaining to you all the solution to this GFG Daily problem. Here in my channel, I will upload many others coding problem solutions as well. So please Subscribe. Thanks.
Рекомендации по теме
Комментарии
Автор

struct Trie{
int w;// store the count of word at that point.
Trie* v[26];
Trie(){
w=0;
for(int i=0;i<26;i++) v[i]=nullptr;
}
};

class Solution
{
private:
Trie *root;

public:
Solution(){
root=new Trie();
}

vector<string> findPrefixes(string arr[], int n)
{
vector<string> ans;
for(int i=0;i<n;i++) insert(arr[i]);
for(int i=0;i<n;i++){

}
return ans;
}

void insert(string s){
Trie* r=root;
for(auto i:s){
if(!r->v[i-'a']){
r->v[i-'a']=new Trie();
}
r=r->v[i-'a'];
r->w++;
}
}

string search(string s){
Trie* r=root;
string a="";
for(auto i:s){
if(r->w==1) return a;
a+=i;
r=r->v[i-'a'];
}
return a;
}
};

codenow