-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDistinctSubstrings.java
63 lines (57 loc) · 1.44 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*https://binarysearch.com/problems/Distinct-Substrings*/
/*https://practice.geeksforgeeks.org/problems/count-of-distinct-substrings/1*/
import java.util.*;
class TrieNode
{
boolean endOfWord;
TrieNode[] hash = new TrieNode[26];
}
class Trie
{
TrieNode root;
Trie()
{
root = new TrieNode();
}
public void addWord(String s)
{
int i = 0;
TrieNode temp = root;
for (; i < s.length(); ++i)
{
if (temp.hash[s.charAt(i)-'a'] == null)
temp.hash[s.charAt(i)-'a'] = new TrieNode();
temp = temp.hash[s.charAt(i)-'a'];
temp.endOfWord = true;
}
}
public int check(String s, int index)
{
int i, result = 0;
TrieNode temp = root;
boolean flag = false;
for (i = index; i < s.length(); ++i)
{
if (temp.hash[s.charAt(i)-'a'] == null)
{
temp.hash[s.charAt(i)-'a'] = new TrieNode();
flag = true;
}
temp = temp.hash[s.charAt(i)-'a'];
if (flag) ++result;
}
return result;
}
}
class Solution {
Set<String> set;
public int solve(String s) {
set = new HashSet<String>();
int n = s.length(), i, j, result = s.length();
Trie trie = new Trie();
trie.addWord(s);
for (i = 1; i < n; ++i)
result += trie.check(s,i);
return result;
}
}