-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
83 lines (51 loc) · 1.37 KB
/
Main.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
/**
* @author leon on 2018/5/31.
* @version 1.0
*/
import java.util.Arrays;
public class Main {
public String abs = "asd";
String sss = "aaa";
public static void main(String[] args) {
String a="ABCDABEABCDAF";
int [] b =getNext1(a);
int [] c =getNext2(a);
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(c));
}
public static int[] getNext1(String ps) {
char[] p = ps.toCharArray();
int[] next = new int[p.length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < p.length - 1) {
if (k == -1 || p[j] == p[k]) {
// 当两个字符相等时要跳过
if (p[++j] == p[++k]) {
next[j] = next[k];
} else {
next[j] = k;
}
} else {
k = next[k];
}
}
return next;
}
public static int[] getNext2(String ps) {
char[] p = ps.toCharArray();
int[] next = new int[p.length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < p.length - 1) {
if (k == -1 || p[j] == p[k]) {
next[++j] = ++k;
} else {
k = next[k];
}
}
return next;
}
}