演算法的核心是部分匹配表和回退演算法,部分匹配表的實作如下:
function kmpGetStrPartMatchValue(str) {
var prefix = [];
var c =0,j=str.length;i
var newStr = str.substring(0,i 1);
partMatch[ i] = 0;
} else {
for(var k=0;k suffix [k] = newStr.slice(-k-1);
if(prefix[k]== suffix ] = prefix[k].length;
}
}
if(!partMatch[i]){ }
}
prefix.length = 0
;
prefix.length = 0
;
;
; suffix.length = 0;
return partMatch;
}
//demo
var t="ABCDABD";console.log(kmpGetStrPartMatchValue(t));//output:[0,0,0,0,1,2,0 ]
回退演算法實作如下:
複製程式碼
程式碼如下: >function KMP(sourceStr,targetStr){ var partMatchValue = kmpGetStrPartMatchValue(targetStr);
var result = false;
fmmo; ;i ){
for(var m=0,n=targetStr.length;m > if(m == targetStr.length-1){
break;
} else { } else {
(m>0 && partMatchValue[m-1] > 0){
m = partMatch }🎜> break;
> }
if(result){
result;
}
var s = "BBC ABCDAB ABCDABCDABDE";
var t = "ABCDABD";
console.log(KMP(s,t));
//output: true