实现strStr()--indexOf()方法

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

function strStr(haystack, needle) {
    if(needle.length == 0){
        return 0
    }
    if(haystack.length == 0){
        return -1
    }
    let len = needle.length,firstChar = needle[0]
    for(let i = 0;i < haystack.length;i++){
        let item = haystack[i]
        if(item == firstChar && haystack.substr(i,len) == needle){
            return i
        }
    }
    return -1
}

Leecode提交通过

原文地址:https://www.cnblogs.com/zhenjianyu/p/13174107.html