如题= =自用模板

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
/*子串在母串出现次数 子串前缀出现次数*/
class KMP{
int maxn=100050;
int[] Next=new int[maxn];
void kmp_pre(String x, int len1, int Next[]) {
int i, j;
j = Next[0] = -1;
i = 0;
while (i < len1) {
while (-1 != j && x.charAt(i) != x.charAt(j)) j = Next[j];
Next[++i] = ++j;
}
}
long KMP_Count(String x, int len1, String y, int len2) {
int i, j;
long ans = 0;
kmp_pre(x, len1, Next);
i = j = 0;
while (i < len2) {
//匹配完的前缀下标为0~j-1 长度为j
while (-1 != j && y.charAt(i) != x.charAt(j)) {
j = Next[j];
}
i++;
j++;
if (j >= len1) {
j = Next[j];
ans++;
}
}
/*while(j!=-1){
j=Next[j];
} 如果还有为匹配完的前缀*/
return ans;
}
}
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
/*最长回文子串 最长重复子串*/
class EXKMP{
int maxn=100050;
int[] Next=new int[maxn];
int[] ex=new int[maxn];
//ex[i] T串从i到tlen-1 这一段中和S串具有的最长公共前缀的长度;
void kmp(String P){
int m=P.length();
Next[0]=m;
int j=0,k=1;
while(j+1<m&&P.charAt(j)==P.charAt(j+1)) j++;
Next[1]=j;
for(int i=2; i<m; i++){
int p=Next[k]+k-1;
int L=Next[i-k];
if(i+L<p+1) Next[i]=L;
else{
j=Math.max(0,p-i+1);
while(i+j<m&&P.charAt(i+j)==P.charAt(j))
j++;
Next[i]=j;
k=i;
}
}
}

void exkmp(String P,String T){
int m=P.length();
int n=T.length();
kmp(P);
int j=0,k=0;
while(j<n&&j<m&&P.charAt(j)==T.charAt(j))
j++;
ex[0]=j;
for(int i=1; i<n; i++){
int p=ex[k]+k-1;
int L=Next[i-k];
if(i+L<p+1)
ex[i]=L;
else
{
j=Math.max(0,p-i+1);
while(i+j<n&&j<m&&T.charAt(i+j)==P.charAt(j))
j++;
ex[i]=j;
k=i;
}
}
}
}