Count of Strings of Array having given prefixes for Q query
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
String[] words
= {
"geekf"
,
"geeks"
,
"geeksforgeeks"
,
"string"
,
"strong"
};
String[] queries = {
"geek"
,
"gel"
,
"str"
};
ArrayList<Integer> ans
= GeekAndString(words, queries);
for
(
int
count : ans)
System.out.print(count +
" "
);
}
public
static
ArrayList<Integer>
GeekAndString(String[] Li, String[] Queries)
{
ArrayList<Integer> answer =
new
ArrayList<>();
Trie trie =
new
Trie();
for
(String word : Li) {
trie.inert(word);
}
for
(String word : Queries) {
answer.add(trie.query(word));
}
return
answer;
}
}
class
TrieNode {
TrieNode[] links;
int
counter;
TrieNode()
{
this
.links =
new
TrieNode[
26
];
this
.counter =
0
;
}
}
class
Trie {
private
TrieNode root;
Trie() {
this
.root =
new
TrieNode(); }
public
void
inert(String word)
{
TrieNode node = root;
for
(
int
i =
0
; i < word.length(); i++) {
int
pos = (word.charAt(i) -
'a'
);
if
(node.links[pos] ==
null
) {
node.links[pos] =
new
TrieNode();
}
node = node.links[pos];
node.counter = node.counter +
1
;
}
}
public
int
query(String word)
{
TrieNode node = root;
for
(
int
i =
0
; i < word.length(); i++) {
int
pos = (word.charAt(i) -
'a'
);
if
(node.links[pos] ==
null
) {
return
0
;
}
node = node.links[pos];
}
return
node.counter;
}
}
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
String[] words
= {
"geekf"
,
"geeks"
,
"geeksforgeeks"
,
"string"
,
"strong"
};
String[] queries = {
"geek"
,
"gel"
,
"str"
};
ArrayList<Integer> ans
= GeekAndString(words, queries);
for
(
int
count : ans)
System.out.print(count +
" "
);
}
public
static
ArrayList<Integer>
GeekAndString(String[] Li, String[] Queries)
{
ArrayList<Integer> answer =
new
ArrayList<>();
Trie trie =
new
Trie();
for
(String word : Li) {
trie.inert(word);
}
for
(String word : Queries) {
answer.add(trie.query(word));
}
return
answer;
}
}
class
TrieNode {
TrieNode[] links;
int
counter;
TrieNode()
{
this
.links =
new
TrieNode[
26
];
this
.counter =
0
;
}
}
class
Trie {
private
TrieNode root;
Trie() {
this
.root =
new
TrieNode(); }
public
void
inert(String word)
{
TrieNode node = root;
for
(
int
i =
0
; i < word.length(); i++) {
int
pos = (word.charAt(i) -
'a'
);
if
(node.links[pos] ==
null
) {
node.links[pos] =
new
TrieNode();
}
node = node.links[pos];
node.counter = node.counter +
1
;
}
}
public
int
query(String word)
{
TrieNode node = root;
for
(
int
i =
0
; i < word.length(); i++) {
int
pos = (word.charAt(i) -
'a'
);
if
(node.links[pos] ==
null
) {
return
0
;
}
node = node.links[pos];
}
return
node.counter;
}
}