28. Implement strStr()(js)

28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
题意:实现一个函数strStr(),接收两个参数,haystack中是否存在needle子串,存在则返回needle首字符在haystack中的索引,不存在则返回-1
代码如下:
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    let hLen=haystack.length;
    let nLen=needle.length;
    let str='';
    for(var i=0;i<=hLen-nLen;i++){
        str=haystack.slice(i,nLen+i);
        if( str === needle) return i;
    }
    return -1
};

 

posted @ 2019-02-17 21:49  mingL  阅读(117)  评论(0编辑  收藏  举报