实现 strStr() 函数。

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

示例 1:

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

示例 2:

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

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr


第一种方法:不过这样写就没有做这题的意义了

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
    return haystack.indexOf(needle)
};

第二种方法:速度比较慢

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
    //定义索引
    index = -1;
    //如果needle长度为0 则直接返回0
    if (!needle) return 0;
    //循环
    for (let i = 0; i < haystack.length; i++) {
    //如果当前循环的字符等于needle的第一个字符则再次循环
        if (haystack[i] == needle[0]) {
    //记录索引
            index = i;
    //循环
            for (let j = 0; j < needle.length; j++) {
    //判断haystack索引往后的needle长度的位数,两个字符串是否一致
                if (needle[j] != haystack[i + j]) {
    //如果出现不一致则索引为-1
                    index = -1;
                    break;
                }
            }
    //如果能跑完内部循环,说明needle在index位置出现,直接返回index。要判断index是否为-1
            if (index >= 0) return index;
        }
    }
    return index;
};

第三种方法:用到了substr函数

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
    if (!needle) return 0;
    let needleLen = needle.length;
    for (let i = 0; i < haystack.length; i++) {
        if (haystack.substr(i, needleLen) == needle) {
            return i;
        }
    }
    return -1;
};