The core of the algorithm is partial matching tables and rollback algorithms. The implementation of partial matching tables is as follows:
Copy codeThe Code is 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, 1, 2, 0]
The rollback algorithm is implemented as follows:Copy codeCode: 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