-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringSearchZFunction.java
More file actions
57 lines (47 loc) · 1.31 KB
/
StringSearchZFunction.java
File metadata and controls
57 lines (47 loc) · 1.31 KB
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
public class StringSearchZFunction {
}
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length() + needle.length() + 1;
int nn = needle.length();
String s = needle + "$" + haystack;
char[] sc = s.toCharArray();
int[] zarr = new int[n];
if(nn == 0) {
return 0;
}
int result = -1, l=0, r=0;
boolean resultFound = false;
int count = 0;
int i,j;
for(int k=1; k<n; k++) {
// System.out.println("K IS " + k);
if(k <= r && r-k > zarr[k-l]) {
zarr[k] = zarr[k-l];
} else {
count = 0;
i = 0;
j = k;
while(j < n && sc[i] == sc[j]) {
l=k;
r=j;
count++;
// System.out.println("Comparing " + sc[i] + " " + sc[j] + " " + count);
i++;
j++;
}
zarr[k] = count;
if(count == nn) {
break;
}
}
}
for(int k=nn+1; k<n; k++) {
if(zarr[k] == nn) {
result = k-nn-1;
break;
}
}
return result;
}
}