题目
上一题中的字符串"BAAABBBAA",与目标"BAAABBBCDDDCCHHHHBBBAAABBBAADD"进行匹配,至少需要多少次字符匹配(提示:利用优化后的Next数组):
The string in question above “BAAABBBAA” matches with “BAAABBBCDDDCCHHHHBBBAAABBBAADD”. How many times character matching will need at least? (Hint: Use “Next” arrays ):
答案
31
过程
先来回忆一下计算next数组的代码
优化前的
int *findNext(string P) {
int j, k;
int m = P.length();
assert(m > 0);
int *next = new int[m];
assert(next != 0);
next[0] = -1;
j = 0, k = -1;
while (j < m - 1) {
while (k >= 0 && P[k] != P[j])
k = next[k];
j++;
k++;
next[j] = k;
}
return next;
}
优化后的
int *findNext(string P) {
int j, k;
int m = P.length();
assert(m > 0);
int *next = new int[m];
assert(next != 0);
next[0] = -1;
j = 0, k = -1;
while (j < m - 1) {
while (k >= 0 && P[k] != P[j])
k = next[k];
j++;
k++;
//有区别的地方
if(P[k]==P[j]){
next[j]=next[k]
}else{
next[j]=k;
}
}
return next;
}
解答过程
1.先求出优化前的next数组,下标含义是前面串的串首和串尾的相同字符个数,
以j=8为例,[BA]AABB[BA],括号里面的相等,所以next[8]=2。
2.根据优化前的next数组求出优化后的next数组,按照这段代码计算
if(P[k]==P[j]){
next[j]=next[k]
}else{
next[j]=k;
}
1.如果Pk!=Pj,next[j]=k
以j=1为例,此时k是优化前的next[j]=0,Pj=P1=‘A’,Pk=P0=‘B’,所以,next[1]=0
2.如果Pk==Pj,next[j]=next[k]
以j=4为例,k=0,next[4]=next[0]=-1
然后匹配