-
Notifications
You must be signed in to change notification settings - Fork 1
/
PatternSearchingTrie.java
85 lines (71 loc) · 2.06 KB
/
PatternSearchingTrie.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Problem : https://www.geeksforgeeks.org/pattern-searching-using-trie-suffixes/
*/
import java.util.List;
import java.util.LinkedList;
class TrieNode {
public static final int SIZE = 256;
List<Integer> indices;
TrieNode[] next;
public TrieNode() {
indices = new LinkedList<>();
next = new TrieNode[SIZE];
}
}
class SuffixTrie {
TrieNode root;
public SuffixTrie() {
root = new TrieNode();
}
private void insertSuffix(String word, int startIndex) {
if (word == null) {
throw new IllegalArgumentException();
}
TrieNode temp = root;
for (int i = 0; i < word.length(); ++i) {
temp.indices.add(startIndex + i);
if (temp.next[word.charAt(i)] == null) {
temp.next[word.charAt(i)] = new TrieNode();
}
temp = temp.next[word.charAt(i)];
}
}
public void insert(String word) {
if (word == null) {
throw new IllegalArgumentException();
}
for (int i = 0; i < word.length(); ++i) {
insertSuffix(word.substring(i), i);
}
}
public List<Integer> search(String word) {
if (word == null) {
throw new IllegalArgumentException();
}
TrieNode temp = root;
for (int i = 0; i < word.length(); ++i) {
char c = word.charAt(i);
if (temp.next[c] == null) {
return null;
}
temp = temp.next[c];
}
return temp.indices;
}
}
public class PatternSearchingTrie {
public static void main(String[] args) {
String word = "thisisarandomstring";
SuffixTrie trie = new SuffixTrie();
trie.insert(word);
String pattern = "s";
List<Integer> indices = trie.search(pattern);
if (indices != null) {
for (int i : indices) {
System.out.println(i - pattern.length());
}
} else {
System.out.println(pattern + " not found in " + word);
}
}
}