Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思路:KMP算法算是忘得一干二净,回头有时间看看,自己实现了一个复杂度高的,即从源字串中第一个开始遍历,把目标字串的每一个字符和源字串比对,若相同则找到,若不同,则跳出内存循环,从源字串的第二个字符再开始比对。

收获:注意区分haystack=NULL和haystack=""的区别。实际上NULL即0,也就是空指针,所以当haystack=NULL的时候,它是不指向任何东西的,所对应的内存也是空的;

而当haystack="";等价于haystack="",此时该指针是确实指向了内存中某个区域的,所以我们对该指针进行操作,是不会出错的,而对空指针的任何操作都是没有定义的

特殊用例:haystack="";needle="";可以在haystack的第一个字符找到目标字符串,所以返回不是NULL,而是"",也即"".

代码:

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(!haystack||!needle)
            return NULL;
        int len_h=strlen(haystack);
        int len_n=strlen(needle);
        if(len_h==0&&len_n==0)
            return haystack;
        else if(len_h!=0&&len_n==0)
            return (haystack+len_h-1);
        int i;
        int inlayer_i;
        int j=0;
        for(i=0;i<=len_h-len_n;++i)
        {
            inlayer_i=i;
            j=0;
            while(inlayer_i<len_h&&j<len_n&&(*(haystack+inlayer_i)==*(needle+j)))
            {
                ++inlayer_i;
                ++j;
            }
            if(j==len_n)
                return haystack+i;
        }   
        return NULL;
            
    }
};
原文地址:https://www.cnblogs.com/fightformylife/p/4053440.html