萌辣

文章 评论 浏览 29

萌辣 2022-05-04 13:56:22

首先是用了slice的 这个贼简单:

function matching(n, str, m, match){
	if(m>n){
		return -1;
	}

	for(let i = 0; i<n-m+1; i++){
		if(str.slice(i,i+m)===match){
			return i;

		}
	}
	return -1;
}

然后我也记得我本科的时候算法课专门有节课讲了pattern matching 回去找了下课件果然是KMP 我结合了阮老师的这个http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html 下面是我KMP的写法:

function partialMatchTable(str, n){
	let res = [0];
	let k = 0;
	for(let i=1; i<n; i++){
		while(k>0&&str[k]!==str[i]){
			k = res[k-1];
		}
		if(str[k]===str[i]){
			k += 1
		}
		res.push(k);

	}
	return res;

}

function KMP(n, str, m, match){
        if(m>n) return -1;
	let index = 0;
	let table = partialMatchTable(match, n);
        console.log(table);
	while(index<n){
		let same = 0;
		let index2 = 0;
		while(str[index+index2]===match[index2]&&index2<m){
			same += 1;
			index2 += 1;
		}
		if(same===m){
			return index;
		}
        if(same===0){
        	index += 1;
        }else{
        	index += same - table[same-1];
        }

	}
	return -1;
}

console.log(KMP(15, "ABDCABABDCABDCB", 7, "ABDCABD")) 

结果在这里哈:
Screen Shot 2020-03-05 at 11 05 03 PM

欢迎指正!!

第 71 题: 实现一个字符串匹配算法,从长度为 n 的字符串 S 中,查找是否存在字符串 T,T 的长度是 m,若存在返回所在位置

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文