LeetCode 实现 strStr() 函数

题目描述

实现 strStr() 函数。

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

示例一:

输入: haystack = “hello”, needle = “ll”
输出: 2

示例二:

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

js代码:

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
     if(!needle || needle.length <1){return 0}

    if(needle.length > haystack.length){

        return -1;

    }

    let subStr = '';

    for(let i=0,len=haystack.length;i<len;i++){

        if(haystack[i] === needle[0]){

            subStr = haystack.substr(i,needle.length);

            if(subStr == needle){

                return i;

            }

        }

    }

    return -1;
};

运行结果:
在这里插入图片描述

发布了57 篇原创文章 · 获赞 22 · 访问量 7279

猜你喜欢

转载自blog.csdn.net/qq_39897978/article/details/99062348