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

  

posted on 2017-07-08 08:05  Hugh_Sun  阅读(119)  评论(0编辑  收藏  举报

导航