public int kmp(String t, String p) {
if("".equals(p))
return 0;
//主串
char[] tt = t.toCharArray();
//匹配串
char[] pp = p.toCharArray();
//next数组
int[] next = new int[pp.length];
next[0] = -1;
int i = 0;
int k = -1;
while(i < pp.length -1)
if(-1 == k || pp[i] == pp[k])
if(pp[++i] == pp[++k])
next[i] = next[k];
else
next[i] = k;
else
k = next[k];
//字符串匹配
int a = 0;
int b = 0;
while(a < tt.length && b < pp.length) {
if(-1 == b || tt[a] == pp[b]) {
a++;
b++;
} else
b = next[b];
}
if(b == pp.length)
return a - b;
return -1;
}
10-10
718
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-25
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交