Implement strStr()

Implement strStr().

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

class Solution {
public:
     char *strStr( char *haystack,  char *needle) 
    {
         // BF
         /*
        for(char* pstart=haystack;(*pstart)!=NULL;pstart++)
        {
            char* p2=needle;
            for(char* p1=pstart;(*p1)!=NULL && (*p2)!=NULL;p1++,p2++)
            {
                if((*p1)!=(*p2)) break;
            }
            if((*p2)==NULL) return pstart;
        }
        return NULL;
        
*/
        
         // KMP
         int len=strlen(needle);
         if(len== 0return haystack;
         int* find= new  int[len];
        find[ 0]= 0;
         for( int i= 1,j= 0;i<len;i++)
        {
             while(j> 0 && needle[i]!=needle[j]) j=find[j- 1];
             if(needle[i]==needle[j]) j++;
            find[i]=j;
        }
         int textlen=strlen(haystack);
         for( int i= 0,j= 0;i<textlen;i++)
        {
             while(j> 0 && haystack[i]!=needle[j]) j=find[j- 1];
             if(haystack[i]==needle[j]) j++;
             if(j==len)  return haystack+i-len+ 1;
        }
         return NULL;
    }
};

 


你可能感兴趣的:(imp)