-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountAllUniqueSubstrings.java
70 lines (61 loc) · 2.16 KB
/
CountAllUniqueSubstrings.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
package Tries;
public class CountAllUniqueSubstrings {
static class Node {
Node[] children = new Node[26];
boolean endOfWord = false;
Node() {
for (int i = 0; i < 26; i++) {
// by default these are null values
children[i] = null;
}
}
}
// declaring empty Root node
public static Node root = new Node();
// Insert into trie
public static void insert(String word){ //O[L]
Node curr = root;
for (int level = 0; level <word.length(); level++){
int index = word.charAt(level) - 'a';
if (curr.children[index] == null){
// create node : if does not exist
curr.children[index] = new Node();
}
curr = curr.children[index];
}
curr.endOfWord = true;
}
// Search into trie
public static boolean search(String key){
Node curr = root;
for (int level=0; level<key.length(); level++){
int index = key.charAt(level) - 'a';
if (curr.children[index] == null){
// last condition
return false;
}
curr = curr.children[index];
}
if (curr.endOfWord == true) return true;
else return false;
}
public static int countSubs(Node root){
if (root == null) return 0;
int count = 0;
for (int i=0; i<26; i++){
if (root.children[i] != null){
count += countSubs(root.children[i]);
}
}
return count+1;
}
public static void main(String[] args) {
String str = "ababa";
//inserting all suffixes
for (int i=0; i<str.length(); i++){
String suffix = str.substring(i);
insert(suffix);
}
System.out.println(countSubs(root));
}
}