-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeeks and string:-geeksforgeeks
48 lines (43 loc) · 1.11 KB
/
Geeks and string:-geeksforgeeks
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
class Solution{
public:
int x;
struct trie{
int cnt;
trie* ch[26];
trie(){
cnt = 0;
for(int i = 0;i < 26;i++)
ch[i] = NULL;
}
};
void build(string a[], trie *root){
trie *temp;
for(int i = 0;i < x;i++){
temp = root;
for(int j = 0;j < a[i].size();j++){
if(temp->ch[a[i][j]-'a'] == NULL)
temp->ch[a[i][j]-'a'] = new trie();
temp->ch[a[i][j]-'a']->cnt += 1;
temp = temp->ch[a[i][j]-'a'];
}
}
}
int find(string s, trie *root){
for(int i = 0;i < s.size();i++){
if(root->ch[s[i]-'a'] == NULL)
return 0;
root = root->ch[s[i]-'a'];
}
return root->cnt;
}
vector<int> prefixCount(int N, int Q, string li[], string query[])
{
vector<int> res;
x = N;
trie *root = new trie();
build(li, root);
for(int i = 0;i < Q;i++)
res.push_back(find(query[i], root));
return res;
}
};