[LeetCode][算法初级][字符串]38 实现strStr()

https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/38/

也就是一个查找子串的问题,思路很容易想到,从两个字符串相同的第一个字符开始往后比较,

如果遇到不同的字符则结束本次比较,将大字符串的指针后移,并重复此过程。

我一开始的实现是这样的:

int strStr(char* haystack, char* needle) {
char * hay = haystack;
char * haytmp ;
char * nd = needle;
if(!*nd)
    return 0;
while(*hay){
    haytmp = hay;
    while(*haytmp==*nd && *haytmp && *nd){
        haytmp++;
        nd++;       
    }
    if(*nd){
        hay++;
        nd = needle;
    }
    else{
        return strlen(haystack) - strlen(hay);

    }
}
return -1;
}

结果执行完所有的case需要400多毫秒,我不服啊,看了下只需要4ms的算法:

int strStr(char* haystack, char* needle) {
char *hay = haystack;
char * nd = needle;
char * haytmp = hay;
if(!*needle)
    return 0;
while(*hay){        
    if(*haytmp==*nd){
        haytmp++;
        nd++;
        if(*nd=='\0')
            return strlen(haystack)-strlen(hay);
        if(*haytmp=='\0')
            return -1;
    }else{        
        hay++;
        haytmp = hay;
        nd=needle;
    }
}
return -1;
}

看了下好像没有什么不同啊?只不过我的多了一个while循环,但也不影响执行次数啊,就算有影响也不至于是100倍的差距吧。

纠结了很久,以为是while循环的玄机,于是到StackOverflow上提问,几分钟内得到了热心群众的回答。

原来第二个解法在haystack遍历到结束都没有找到子串时就会终止程序返回-1,而我的解法还会继续傻傻继续。

哎~多么简单的一个问题,还是太浮躁了。

修改后的我的算法贴一下:

int strStr(char* haystack, char* needle) {
char * hay = haystack;
char * haytmp ;
char * nd = needle;
if(!*nd)
    return 0;
while(*hay){
    haytmp = hay;
    while(*haytmp==*nd && *haytmp && *nd){
        haytmp++;
        nd++;       
    }
    if(*nd){
        if(!*haytmp) return -1; //就加了这句
        hay++;
        nd = needle;
    }
    else{
        return strlen(haystack) - strlen(hay);

    }
}
return -1;
}
执行之下,结果只需要0ms。。。超过100%的提交。果然这就是罪魁祸首了。

猜你喜欢

转载自blog.csdn.net/lokira518/article/details/80301167