Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit beee84b

Browse files
authored
Added pattern searching using trie
1 parent 497e463 commit beee84b

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import java.util.LinkedList;
2+
import java.util.List;
3+
class SuffixTrieNode {
4+
5+
final static int MAX_CHAR = 256;
6+
7+
SuffixTrieNode[] children = new SuffixTrieNode[MAX_CHAR];
8+
List<Integer> indexes;
9+
10+
SuffixTrieNode()
11+
{
12+
13+
indexes = new LinkedList<Integer>();
14+
15+
for (int i = 0; i < MAX_CHAR; i++)
16+
children[i] = null;
17+
}
18+
19+
20+
void insertSuffix(String s, int index) {
21+
22+
23+
indexes.add(index);
24+
25+
26+
if (s.length() > 0) {
27+
28+
29+
char cIndex = s.charAt(0);
30+
31+
32+
33+
if (children[cIndex] == null)
34+
children[cIndex] = new SuffixTrieNode();
35+
36+
// Recur for next suffix
37+
children[cIndex].insertSuffix(s.substring(1),
38+
index + 1);
39+
}
40+
}
41+
42+
43+
List<Integer> search(String s) {
44+
45+
46+
if (s.length() == 0)
47+
return indexes;
48+
49+
50+
if (children[s.charAt(0)] != null)
51+
return (children[s.charAt(0)]).search(s.substring(1));
52+
53+
54+
else
55+
return null;
56+
}
57+
}
58+
59+
// A Trie of all suffixes
60+
class Suffix_tree{
61+
62+
SuffixTrieNode root = new SuffixTrieNode();
63+
64+
65+
Suffix_tree(String txt) {
66+
67+
68+
for (int i = 0; i < txt.length(); i++)
69+
root.insertSuffix(txt.substring(i), i);
70+
}
71+
72+
void search_tree(String pat) {
73+
74+
75+
List<Integer> result = root.search(pat);
76+
77+
78+
if (result == null)
79+
System.out.println("Pattern not found");
80+
else {
81+
82+
int patLen = pat.length();
83+
84+
for (Integer i : result)
85+
System.out.println("Pattern found at position " +
86+
(i - patLen));
87+
}
88+
}
89+
90+
91+
public static void main(String args[]) {
92+
93+
94+
String txt = "geeksforgeeks.org";
95+
Suffix_tree S = new Suffix_tree(txt);
96+
97+
System.out.println("Search for 'ee'");
98+
S.search_tree("ee");
99+
100+
System.out.println("\nSearch for 'geek'");
101+
S.search_tree("geek");
102+
103+
System.out.println("\nSearch for 'quiz'");
104+
S.search_tree("quiz");
105+
106+
System.out.println("\nSearch for 'forgeeks'");
107+
S.search_tree("forgeeks");
108+
}
109+
}

0 commit comments

Comments
 (0)