Skip to content

Commit 39a597b

Browse files
committed
implemented Z algorithm for pattern matching :)
1 parent 517e0ef commit 39a597b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.jumbuna.algs;
2+
3+
import com.jumbuna.ds.Vector;
4+
5+
public class Zalgorithm {
6+
public static Vector<Integer> subStringSearch(String text, String pattern, char separator) {
7+
String concated = pattern + separator + text;
8+
Vector<Integer> zArray = new Vector<>();
9+
Vector<Integer> vec = new Vector<>();
10+
//(m+n) time Z-array construction
11+
zArray.insert(0);
12+
int i = 0;
13+
for(int j = 1; j < concated.length(); j++) {
14+
int startIndex = j + i;
15+
while(concated.charAt(startIndex) == concated.charAt(i) && startIndex < concated.length()) {
16+
++i;
17+
++startIndex;
18+
}
19+
zArray.insert(i);
20+
if(i == pattern.length()) {
21+
vec.insert(zArray.size()-2-pattern.length());
22+
}
23+
if(i <= 1) {
24+
i = 0;
25+
}else {
26+
int k = 1;
27+
for(; (zArray.elementAt(k) + j + k) < startIndex && k < i; k++) {
28+
zArray.insert(zArray.elementAt(k));
29+
++j;
30+
}
31+
if(k == i) {
32+
i = 0;
33+
--j;
34+
}else {
35+
i = zArray.elementAt(k);
36+
}
37+
}
38+
}
39+
40+
return vec;
41+
}
42+
43+
public static void main(String[] args) {
44+
Vector<Integer> vec = Zalgorithm.subStringSearch("abacaccdaabaabad", "aba", '&');
45+
for(int i = 0; i < vec.size(); i++) {
46+
System.out.println(vec.elementAt(i));
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)