-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2416.java
More file actions
88 lines (71 loc) · 1.92 KB
/
LC2416.java
File metadata and controls
88 lines (71 loc) · 1.92 KB
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
/*
* LC2416
*/
import java.util.*;
class Node {
Node child[];
int count;
Node() {
child = new Node[26]; // 0 to 9 digits
count = 0;
}
}
class Trie {
Node root;
Trie() {
root = new Node();
}
public void addWord(String word) {
Node temp = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (temp.child[index] == null) {
temp.child[index] = new Node();
}
temp.child[index].count++;
temp = temp.child[index];
}
}
public int findPrefixCount(String word) {
Node temp = root;
int count = 0;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
count = count + temp.child[index].count;
temp = temp.child[index];
}
return count;
}
}
public class LC2416 {
public static int[] sumPrefixScores(String[] words) {
Trie trie = new Trie();
int count[] = new int[words.length]; // result
for (String word : words) {
trie.addWord(word); // insert in prefix trie
}
int index = 0;
for (String word : words) {
count[index] = trie.findPrefixCount(word);
index++;
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size = sc.nextInt();
sc.nextLine();
System.out.println();
String str[] = new String[size];
System.out.println("Enter the String Here : ");
for (int i = 0; i < str.length; i++) {
System.out.printf("[%d] : ", i);
str[i] = sc.nextLine();
}
System.out.println();
int ans[] = sumPrefixScores(str);
System.out.println(Arrays.toString(ans));
sc.close();
}
}