The core of the algorithm is the partial matching table and the fallback algorithm, and some matching tables are implemented as follows:
Copy Code code as follows:
function Kmpgetstrpartmatchvalue (str) {
var prefix = [];
var suffix = [];
var partmatch = [];
for (Var i=0,j=str.length;i<j;i++) {
var newstr = str.substring (0,i+1);
if (newstr.length = = 1) {
Partmatch[i] = 0;
} else {
for (Var k=0;k<i;k++) {
Prefix[k] = Newstr.slice (0,k+1);
Suffix[k] = Newstr.slice (-k-1);
if (prefix[k] = = Suffix[k]) {
Partmatch[i] = prefix[k].length;
}
}
if (!partmatch[i]) {
Partmatch[i] = 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]
The fallback algorithm is implemented as follows:
Copy Code code as follows:
function KMP (SOURCESTR,TARGETSTR) {
var partmatchvalue = Kmpgetstrpartmatchvalue (TARGETSTR);
var result = false;
for (Var i=0,j=sourcestr.length;i<j;i++) {
for (Var m=0,n=targetstr.length;m<n;m++) {
if (Str.charat (m) = = Sourcestr.charat (i)) {
if (m = = targetstr.length-1) {
result = true;
Break
} else {
i++;
}
} else {
if (m>0 && partmatchvalue[m-1] > 0) {
m = partmatchvalue[m-1]-1;
} else {
Break
}
}
}
if (result) {
Break
}
}
return result;
}
var s = "BBC abcdab Abcdabcdabde";
var t = "abcdabd";
Console.log (KMP (s,t));
Output:true