28. Implement strStr()

Implement strStr().

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

这道题就是在找一个字符串包不包含另一个字符串,现成的方法很多,如果直接使用会很容易解决问题,不过要是自己实现呢:

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    if (needle==="")
        return 0;
    if (haystack==="")
        return -1;
    var num1 = haystack.length;
    var num2 = needle.length;
    if (num2>num1)
        return -1;
    if (num1===num2&&haystack==needle)
        return 0;
    var p1 = 0;
    var p2 = 0;
    var p3 = 0;
    while(p2

你可能感兴趣的:(28. Implement strStr())