Leetcode---28. Implement strStr()

Posted Hugh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode---28. Implement strStr()相关的知识,希望对你有一定的参考价值。

Description

Implement strStr().

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

 

Solution

https://leetcode.com/submissions/detail/108761593/

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    var h_length = haystack.length,
        n_length = needle.length;
    for(var i=0; ;i++) {
        for(var j=0; ; j++) {
            if(j == n_length) 
                return i;
            if(h_length-n_length < i)
                return -1
            if(haystack.charAt(i+j) != needle.charAt(j)) {
                break;
            }
        }
    }    
};

  

以上是关于Leetcode---28. Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode---28. Implement strStr()

44. leetcode 28. Implement strStr()

leetcode 28. Implement strStr()

19.1.30 [LeetCode 28] Implement strStr()

LeetCode 28: Implement Strstr

LeetCode 28. Implement strStr()