Implement strStr() - Javascript

Implement strStr().

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

Tags

Two Pointers, String

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Cheat one line solution by using Javascript API

// Solution 1
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
    return haystack.indexOf(needle);
};


Without using the JS API, mimic the window slider.

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    if(haystack === "") {
        return needle === "" ? 0 : -1;
    }
    
    if(needle === "") {
        return 0;
    }
    
    //Guarantee haystack non-empty
    var len1 = haystack.length;
    var len2 = needle.length;
    
    if(len1



你可能感兴趣的:(Leetcode,Easy,Javascript)