-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay44.java
More file actions
66 lines (53 loc) · 1.54 KB
/
Day44.java
File metadata and controls
66 lines (53 loc) · 1.54 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
import java.util.Scanner;
class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
this.children = new TrieNode[26];
this.isEndOfWord = false;
}
}
class Trie {
TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
public int countDistinctSubstrings() {
return countDistinctSubstrings(root, 0);
}
private int countDistinctSubstrings(TrieNode node, int result) {
for (int i = 0; i < 26; i++) {
if (node.children[i] != null) {
result = countDistinctSubstrings(node.children[i], result + 1);
}
}
return result;
}
}
public class Day44 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
String s = scanner.next();
Trie trie = new Trie();
for (int i = 0; i < s.length(); i++) {
trie.insert(s.substring(i));
}
int distinctSubstrings = trie.countDistinctSubstrings();
System.out.println(distinctSubstrings);
}
scanner.close();
}
}