根据定义手工求模式
a
b
a
a
b
c
a
c的next函数:
(1)next(1)=0
(2)next(2)=1 (t1 =a中不存在真子串,即不存在k满足1<k<2)
(3)next(3)=1 (t1 t2=a b没有重叠真子串)
(4)next(4)=2 (t1 ...t3=a b a有重叠真子串t1 和t3,所以k=2)
(5)next(5)=2 (t1 ...t4=a b a a有重叠真子串t1 和t4,所以k=2)
(6)next(6)=3 (t1 ...t5=a b a a b有重叠真子串t1t2 和t3t4,所以k=3)
(7)next(7)=1 (t1 ...t6=a b a a b c没有重叠真子串)
(8)next(8)=2 (t1 ...t7=a b a a b c a有重叠串t1 和t7,所以k=2)
利用next值表进行匹配的过程:
假设以i和j分别指示主串和模式串中正待比较的字符,若si=tj ,则i和j分别增1,否则,i不变,而j退回到next[j]的位置再比较,若j退回到值为0(即模式的第一个字符失配),则将模式继续向右滑动一个位置,即从主串的下一个字符si+1起和模式重新开始匹配。
从以上的匹配过程可以看出next函数在某些情况下,还可以改进。模式中next[4]=3,意味着s[i]与t[4]不匹配时,s[i]要与t[next[4]]即t[3]匹配,而实际上又存在时t[3]= t[4],显而易见s[i]与t[3]也不匹配,t[2] ,t[1]也同样。
所以next函数可以做这样的改进:在原next基础上,若t[j]=t[k],k=next[k],直到t[j]<>t[k]。在程序中可以不用循环,因为在计算前面的nextval时已经做了修正,只需作nextval[j]= nextval[k]即可。
例题分析
1.设正文长度为n,模式串长度为m,KMP算法的时间复杂度为多少?
O(n+m)
因为尽管从算法上分析最坏的时间复杂度是O(n*m),但在一般情况下,其实际的执行时间近似于O(n+m),因此至今仍被采用。
当目标串为 “0000,0000,0000,0000,00001”,模式串为“0001”,此视为最坏情况。
2.设s为一个长度为n的串,其中的字符各不相同,则s中的互异的非平凡子串(非空且不同于s本身)的个数是多少?
1个字符的子串有n个,两个字符的子串有n-1个,...n-1个字符的子串有2个。
非平凡子串的个数=n+(n-1)+(n-2)+...+3+2=(n(n+1))/2-1
3.设目标为s=”abcaabbabcabaacbacba”,模式p=”abcabaa”。
(1)计算模式p的next函数值。
(2)不写出算法,只画出利用KMP算法(采用next函数值)进行模式匹配时的每一趟的匹配过程。
(1)
j 模式串 next | 1 2 3 4 5 6 7 a b c a b a a 0 1 1 1 2 3 2 |
(2)
第一趟 | a b c a a b b a b c a b a a c b a c b a a b c a b | i=5 j=5 失败next[5]=2 |
第二趟 | a b c a a b b a b c a b a a c b a c b a a b | i=5 j=2 失败next[2]=1 |
第三趟 | a b c a a b b a b c a b a a c b a c b a a b c | i=7 j=3 失败next[3]=1 |
第四趟 | a b c a a b b a b c a b a a c b a c b a a | i=7 j=1 失败next[1]=0 |
第五趟 | a b c a a b b a b c a b a a c b a c b a a b c a b a a | i=15 j=8 成功 |
package zhouqiang.wordfliter;
public class KMP {
String s;
String p;
int[] next;
int times;
int index;
KMP(String s, String p) {
this.s = s;
this.p = p;
this.next = new int[p.length()];
// next数组初始化
for (int i = 0; i < p.length(); i++) {
if (i == 0) {
this.next[i] = -1;
} else if (i == 1) {
this.next[i] = 0;
} else {
this.next[i] = next(p.substring(0, i));
}
}
this.times = 0;
this.index = -1;
}
private int next(String p) {
int length = p.length() / 2;
//循环产生next数组
while (length > 0) {
//当前length个数等于后length个数
if (p.substring(0, length).compareTo(
p.substring((p.length() - length), p.length())) == 0) {
return length;
}
length--;
}
return length;
}
public boolean match() {
int i = 0;
int j = 0;
int index = -1;
//当i小于主字符串和j小于匹配字符串
while (i < this.s.length() && j < this.p.length()) {
//如果存在匹配字符
if (this.s.charAt(i) == this.p.charAt(j)) {
//如果是匹配字符串是第一个
if (j == 0) {
index = i;
}
i++;
j++;
}
//如果字符不匹配
else {
int newj = this.next[j];
//当匹配字符串不是第一个字符 和匹配字符串位置next[j]和j的字符相等
while ((newj != -1)
&& (this.p.charAt(newj) == this.p.charAt(j))) {
newj = this.next[newj];
}
j = newj;
//当不匹配时 如果匹配字符串是第一个
if (j == -1) {
i++;
j = 0;
}
//当不匹配时 如果匹配字符串不是第一个
else {
index = i - j;
}
}
this.times++;
}
//如果存在匹配字符串
if (j == this.p.length()) {
this.index = index;
return true;
}
//如果不存在字符串
else {
return false;
}
}
}