[英]Find substring in string without includes/indexOf/Regex in Javascript
我想弄清楚 substring 是否在字符串中,而不使用 Javascript 的内置方法includes
, indexOf
,(任何类似的)或正则表达式。 基本上只是想学习一种算法方法。
这是我到目前为止所拥有的
function isSubstring(string, substring){
substringIndex = 0;
// loop through string
for(let i = 0; i< string.length; i++){
//check the current substring index if it matches
if(string[i] === substring[substringIndex]){
substringIndex++
//continue searching... Would i then have to call another function recursively?
}
}
}
我无法理解如何构建算法。 一旦找到匹配的第一个字符,我将 go 到下一个,如果它匹配继续到字符串的下一个索引? 然后我需要一个与我当前正在做的循环分开的递归 function 吗? 我正在努力提高算法思维。 谢谢。
许多方法都是可能的。 这是一个:创建一个更简单的函数,该函数将检查first
字符串是否在特定的指定位置,让我们在second
字符串中将其称为start
。 非常简单:对于范围为0到first
-1的所有i
,您将first[i]
与second[start+i]
进行比较。
然后,第二步将是在从0到第二个字符串的长度的所有起始位置重复此功能,同时检查边界(在字符串结束后无法读取)。
当第一个版本可用时,您也可以稍后进行一些优化。 :-)
这是算法算法isSubstring的优化示例。 它仅迭代所需的最少字符数。
例如,如果字符串的长度为20个字符,而子字符串的长度仅为5个字符,则当到达字符串的第16位时,我们可以假定子字符串在字符串中不存在(16 + 5 = 21> 20 )
function isSubstring(str, sub){ if(sub.length > str.length) return false; for(let i = 0; i < str.length - sub.length + 1; i++){ if(str[i] !== sub[0]) continue; let exists = true; for(let j = 1; j < sub.length && exists; j++){ if(str[i+j] === sub[j]) continue; exists = false; } if(exists) return true; } return false; } //expected true console.log(isSubstring("hello world", "hello")); console.log(isSubstring("hello world", "world")); console.log(isSubstring("hello world", "d")); console.log(isSubstring("hello world", "ow")); console.log(isSubstring("hello world", "rl")); console.log(isSubstring("hello world", "")); //expected false console.log(isSubstring("hello world", "hello world 1")); console.log(isSubstring("hello world", "helloo"));
在干草堆length
上的每次迭代中,使用slice
来从该索引中提取字符(索引加针的长度)。 如果切片的字符串与针匹配,则返回true:
function isSubstring(string, substring) { for (let i = 0; i < string.length; i++) { const sliced = string.slice(i, i + substring.length); if (sliced === substring) { return true; } } return false; } console.log(isSubstring('foobar', 'oob')); console.log(isSubstring('foobar', 'baz'));
由于您对递归方法表达了兴趣,因此需要考虑一些事项。 单击黄色的降价部分会显示扰流板。
function f(str, sub, i=0, j=0){
if (j && j == sub.length)
return true;
if (i == str.length)
return false;
if (str[i] == sub[j])
return f(str, sub,
i+1, j+1);
return f(str, sub,
i+1, 0);
}
function isSubstring(str, sub) {
return str.split(sub).length > 1
}
不包括,不包含.indexOf,不包含RegExp。 只是字符串。
只使用一个循环伪代码:
const containSubstr = (str, substr) => { let count = 0; let i = 0; let startIndex = 0; while (i < str.length) { if (substr[count] === str[i]) { if (count === substr.length - 1) { return true; } count++; } else { count = 0; i = startIndex; startIndex++; } i++; } return false; }; console.log(containSubstr("ababad", "abad"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.