,

字符串子串

一、固定长度子串(滑动窗口) 给定字符串 s,截取长度 len 的所有连续子串 逻辑:起点 i 范围 0 ~ …

一、固定长度子串(滑动窗口)

给定字符串 s,截取长度 len 的所有连续子串

逻辑:起点 i 范围 0 ~ s.length - len

function getSubStr(str, len){
	const res=[];
	const n = str.length;
	if(len<=0 || len > n) return res;
	for(let i=0; i<=n-len; i++){
		const sub = str.slice(i,i+len);
		res.push(sub);
	}
	return res;
}

通过for循环和slice截取指定长度字符串,滑动

二、生成字符串所有连续子串

相当于遍历了所有可能的滑动窗口

包含长度 1、2、3… 全部连续片段 思路:外层控制子串长度 L,内层遍历起点 i

function getAllSubStr(s){
	const res=[];
	const n = s.length;
	for(let j = 1;j <= n; j++){
		//相当于遍历了所有可能的滑动窗口
		for(let i=0; i<= n-j; i++){
			const sub = str.slice(i,i+l);
			res.push(sub);
		}
	}
	return res;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

About the Author

每个人都有自己得时区,在自己得时区里,一切都是准时的。

BlockSpare — News, Magazine and Blog Addons for (Gutenberg) Block Editor