题目:
实现 strStr() 函数。 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。 输入:haystack = "hello", needle = "ll" 输出:2 输入:haystack = "aaaaa", needle = "bba" 输出:-1 输入:haystack = "", needle = "" 输出:0
暴力解题:
// @lc code=start
var strStr = function (haystack, needle) {
if (!needle) return 0;
if (haystack.includes(needle)) {
for (let index = 0; index < haystack.length; index++) {
const element = haystack[index];
if (element == needle[0]) {
let flag = true;
for (let i = 0; i < needle.length; i++) {
const item = needle[i];
if (item != haystack[index + i]) {
flag = false;
}
}
if (flag) return index;
}
}
} else {
return -1;
}
};
// @lc code=end
// @lc code=start
var strStr = function (haystack, needle) {
return haystack.indexOf(needle)
};
// @lc code=end
我看题解还有个KMP算法但是我不会所以就先这样吧



