-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question2.java
74 lines (63 loc) · 1.93 KB
/
Question2.java
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
public class Question2 {
//trie datastructure is used here
static class Node{
char ch;
Node[] kids;
int cnt = 0; //to keep track of how many words are going down the same path in Trie
Node(char ch){
this.ch = ch;
this.kids = new Node[26];
}
}
public static int[] sumPrefix(String[] words) {
Node root = new Node('~');
for(String s : words){ //creating the trie
insertInTrie(s, root);
}
int[] ans = new int[words.length];
for(int i = 0; i < words.length; ++i){
ans[i] = getScore(root, words[i]); //calling the getScore function
}
return ans; //prefix score for each string is returned
}
//calculating the prefix score for each string
private static int getScore(Node root, String s){
Node temp = root;
int sum = 0;
for(int i = 0; i < s.length(); ++i){
temp = temp.kids[s.charAt(i) - 'a'];
sum += temp.cnt; //summing the occurence
}
return sum;
}
private static void insertInTrie(String s, Node root){ //creating the trie
Node temp = root;
for(int i = 0; i < s.length(); ++i){ //trversing till the string length
if(temp.kids[s.charAt(i) - 'a'] == null){ //if temp is empty
temp.kids[s.charAt(i) - 'a'] = new Node(s.charAt(i)); //adding the charater at root node
}
temp = temp.kids[s.charAt(i) - 'a'];
temp.cnt++; //incrementing the count of character
}
}
public static void main(String[] args) {
String [] arr= {"abcd","ab","bc","b"};
int[] res=sumPrefix(arr); //calling the function
System.out.print("["+res[0]);
for(int i=1;i<res.length;i++)
{
System.out.print(","+res[i]);
}
System.out.print("]");
}
}
/*
input:
["abc","ab","bc","b"]
output:
[5,4,3,2]
input:
["abcd"]
output:
[4]
*/