-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathL4_DistinctSubstrings_Java
47 lines (42 loc) · 988 Bytes
/
L4_DistinctSubstrings_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
import java.util.ArrayList;
class Node {
Node links[] = new Node[26];
boolean flag = false;
public Node() {
}
boolean containsKey(char ch) {
return (links[ch - 'a'] != null);
}
Node get(char ch) {
return links[ch-'a'];
}
void put(char ch, Node node) {
links[ch-'a'] = node;
}
void setEnd() {
flag = true;
}
boolean isEnd() {
return flag;
}
};
public class Solution
{
public static int countDistinctSubstrings(String s)
{
Node root = new Node();
int n = s.length();
int cnt = 0;
for(int i = 0; i < n;i++) {
Node node = root;
for(int j = i;j<n;j++) {
if(!node.containsKey(s.charAt(j))) {
node.put(s.charAt(j), new Node());
cnt++;
}
node = node.get(s.charAt(j));
}
}
return cnt + 1;
}
}