Skip to main content

28. 实现 strStr()

实现  strStr()  函数。

给你两个字符串  haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回   -1 。

示例 1:

输入:haystack = "hello", needle = "ll"
输出:2

示例 2:

输入:haystack = "aaaaa", needle = "bba"
输出:-1

答案

var strStr = function(haystack, needle) {
const n = haystack.length, m = needle.length;
for (let i = 0; i + needle.length <= haystack.length; i++) {
let flag = true;
for (let j = 0; j < m; j++) {
if (haystack[i + j] != needle[j]) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
};
var haystack = "hello", needle = "ll"
console.log(strStr(haystack,needle))