hello 大家好!今天开写一个新章节,每一天一道算法题。让我们一起来学习算法思维吧!
function strStr(haystack, needle) {
return haystack.indexOf(needle);
}
// 测试示例
const haystack = "sadbutsad";
const needle = "sad";
console.log(strStr(haystack, needle));
function strStr(haystack, needle) {
const n = haystack.length;
const m = needle.length;
for (let i = 0; i <= n - m; i++) {
let j;
for (j = 0; j < m; j++) {
if (haystack[i + j]!== needle[j]) {
break;
}
}
if (j === m) {
return i;
}
}
return -1;
}
// 测试示例
const haystack = "sadbutsad";
const needle = "sad";
console.log(strStr(haystack, needle));