-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext
More file actions
41 lines (40 loc) · 910 Bytes
/
Copy pathNext
File metadata and controls
41 lines (40 loc) · 910 Bytes
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
public static int search(String p, String t) {
// 根据模式字符串获得next数组
int[] next = getNext(p);
int N = t.length();
int M = p.length();
int i = 0;
int j = 0;
while (i < N && j < M) {
if (j == -1 || p.charAt(j) == t.charAt(i)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == M) {
return i - j;
} else {
return -1;
}
}
private static int[] betterGetNext(String p) {
int M = p.length();
int[] next = new int[M];
next[0] = -1;
int j = 0;
int k = -1;
while (j < M - 1) {
if (k == -1 || p.charAt(k) == p.charAt(j)) {
if (p.charAt(k + 1) == p.charAt(j + 1)) {
next[++j] = next[++k];
} else {
next[++j] = ++k;
}
} else {
k = next[k];
}
}
return next;
}