基于KMP算法JavaScript的实现方法分析_基础知识
程序员文章站
2022-05-13 18:09:08
...
算法的核心是部分匹配表和回退算法,部分匹配表的实现如下:
function kmpGetStrPartMatchValue(str) {
var prefix = [];
var suffix = [];
var partMatch = [];
for(var i=0,j=str.length;i var newStr = str.substring(0,i+1);
if(newStr.length == 1){
partMatch[i] = 0;
} else {
for(var k=0;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;
}
回退算法实现如下:
function KMP(sourceStr,targetStr){
var partMatchValue = kmpGetStrPartMatchValue(targetStr);
var result = false;
for(var i=0,j=sourceStr.length;i for(var m=0,n=targetStr.length;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
复制代码 代码如下:
function kmpGetStrPartMatchValue(str) {
var prefix = [];
var suffix = [];
var partMatch = [];
for(var i=0,j=str.length;i
if(newStr.length == 1){
partMatch[i] = 0;
} else {
for(var k=0;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]
回退算法实现如下:
复制代码 代码如下:
function KMP(sourceStr,targetStr){
var partMatchValue = kmpGetStrPartMatchValue(targetStr);
var result = false;
for(var i=0,j=sourceStr.length;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
上一篇: MHA高可用部署及测试
下一篇: sql case 函数与详细说明