【LeetCode】【esay】【28】实现 strStr()

一开始 理解错了 需求 写的有点花了~~~ 

而且 其实 这个题目里面 涉及了一丢丢 小回溯的问题~~!!!

另外  用 indexof 一上来就找到 那个位置 ,某个角度会更好哟!!! 

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

扫描二维码关注公众号,回复: 11266930 查看本文章
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {

    let start = "";

    if(needle.length==0){
        // if(haystack.length==0){
        //     return 0;
        // }else{

        //     return -1;
        // }
        return 0;
    }else if(needle.length==1){
        if(haystack.length==0){
            return -1;
        }else{
            if(haystack.includes(needle)){

                return haystack.indexOf(needle);
            }else{
                return -1;
            }
        }

    }else if(needle==haystack){
        return 0;
    }else if(needle.length>haystack.length){
        return -1;
    }else{

        start = needle.substr(0,1);
    }

    let rsFlg = true;
    let index = -1;

    for(let i = 0 ;i< haystack.length;i++){

        // let tempStr = haystack.substr(i,1);
        if(haystack.substr(i,1)==start){

            index = i;
            // i++;
            // for(let j=1;j<needle.length;i++,j++){
                // console.log(i);
                // console.log(haystack.substr(i,1));
                // console.log(j);
                // console.log(needle.substr(j,1));

                // if(haystack.substr(i,1)!=needle.substr(j,1)){
                //     rsFlg = false;
                //     break;
                // }
            // }
            // console.log(rsFlg);

            if(haystack.substr(i,needle.length)!=needle){
                rsFlg = false;

                if(haystack.substring(index+1).includes(start)){
                    rsFlg = true;
                    // index = -1;
                    continue;
                }else{
                    break;
                }

            }else{

                break;
            }

            // if(rsFlg){
            //     break;
            // }
        }

        // if(!rsFlg){
        //     // i--;
        //     // i--;
        //     if(haystack.substring(index).includes(start)){
        //         rsFlg = true;
        //         // index = -1;
        //         continue;
        //     }else{
        //         break;
        //     }
        //     // continue;
        // }
    }

    if(!rsFlg||(index==-1)){
        return -1;
    }

    return index;

};

猜你喜欢

转载自blog.csdn.net/MENGCHIXIANZI/article/details/106325380