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;
            }
        }
    }    
};

  

原文地址:https://www.cnblogs.com/samo/p/7135654.html