-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Geek and Strings
118 lines (82 loc) · 1.97 KB
/
GFG Geek and Strings
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
111
112
113
114
115
116
117
118
USING TRIE
class Solution{
struct TrieNode{
int value;
TrieNode* arr[26];
};
TrieNode* newNode() {
TrieNode* temp=new TrieNode();
temp->value=0;
for(int i=0;i<26;i++)
{
temp->arr[i]=NULL;
}
return temp;
}
void insert(TrieNode* root,string word)
{
int i=0;
TrieNode* temp=root;
while(i<word.size())
{
if(temp->arr[word[i]-'a']==NULL)
{
temp->arr[word[i]-'a']=newNode();
}
temp=temp->arr[word[i]-'a'];
temp->value++;
i++;
}
}
int prefCount(TrieNode* root,string pref)
{
int i=0;
TrieNode* temp=root;
while(i<pref.size())
{
if(temp->arr[pref[i]-'a']==NULL)
{
return 0;
}
temp=temp->arr[pref[i]-'a'];
i++;
}
int ans=0;
ans=temp->value;
return ans;
}
public:
vector<int> prefixCount(int N, int Q, string li[], string query[])
{
TrieNode* root=newNode();
vector<int> answer(Q,0);
for(int i=0;i<N;i++)
{
string w=li[i];
insert(root,w);
}
for(int i=0;i<Q;i++){
string s=query[i];
answer[i]=prefCount(root,s);
}
return answer;
}
};
//USING MAP
unordered_map<string, int> mp;
for(int i=0; i<Q; i++)
mp[query[i]] = 1;
for(int i=0; i<n; i++)
{
string temp = "", str = li[i];
for(int j=0; j<str.size(); j++)
{
temp += str[j];
if(mp[temp])
mp[temp]++;
}
}
vector<int> ans;
for(int i=0; i<Q; i++)
ans.push_back(mp[query[i]] - 1);
return ans;