Given a list of contacts which exist in a phone directory and a query string str. The task is to implement search query for the phone directory. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday 22 July 2020

Given a list of contacts which exist in a phone directory and a query string str. The task is to implement search query for the phone directory.

Phone directory :print each query result in new line. If there is no match between query and contacts, print "0".

                           Phone directory problem

Given a list of contacts which exist in a phone directory and a query string str. The task is to implement search query for the phone directory. Run a search query for each prefix p of the query string str(i.e from  index 1 to str length) that prints all the distinct recommended contacts which have the same prefix as our query (p) in lexicographical order.

NOTE: If there is no match between query and contacts , print "0".

print each query result in new line. If there is no match between query and contacts, print "0".

Example:
Input:
1
3

geeikistest geeksforgeeks geeksfortest
geeips

Output:

geeikistest geeksforgeeks geeksfortest
geeikistest geeksforgeeks geeksfortest
geeikistest geeksforgeeks geeksfortest
geeikistest
0

0

#include <bits/stdc++.h>
using namespace std;

int main() {
//code
int t;
cin>>t;
while(t--)
{
int n,f;
cin>>n;
vector<string> v;
v.clear();
string s;
for(int i=0;i<n;++i)
{
cin>>s;
v.push_back(s);
}
cin>>s;

int i=0;
//sort string in lexicographical ordered
//so print the in lexicographical
sort(v.begin(),v.end());
//if there is duplicate element
//then uniquify the vector
auto it=std::unique(v.begin(),v.end());
//resize the vector
v.resize(std::distance(v.begin(),it));

while(i<s.size())
{
f=1;
//checking for every string
for(int j=0;j<v.size();++j)
{
// char of s is same as char of v[j] at i position then print
//else vanise the string and set to null.
if(s[i]==v[j][i]&&v[j].size()>0)
{
cout<<v[j]<<" ";
f=0;
}
else{
v[j]="\0";
}
}
++i;
//if not found any matching print just 0.
if(f)cout<<'0'<<" ";

cout<<endl;

}
}
return 0;
}