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

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        int size = 0;
        for(;haystack[size]!='\0' ;size++);
        int size_needle =0;
        while(needle[size_needle]!='\0')size_needle++;
        if(size_needle == 0 )return haystack;
        
        
        vector<int> patten(size_needle,0);
        
        generatepatten(needle,size_needle,patten);
        
        int i = 0;
        int ind = 0;
        while( i < size )
        {
            if(haystack[i] == needle[ind] )
            {
                i++;
                ind++;
                if(ind == size_needle )
                return haystack + i - size_needle;
            }
            else
            {
                i = i - ind + patten[ind] +1;
                ind = 0;
            }
        }
        return NULL;
        
    }
    void generatepatten(char * needle , int size , vector<int> & patten)
    {
        int len = 0;
        for(int i = 1 ; i < size ;i++)
        {
            if(needle[i] == needle[len])
            {
                patten[i] = ++len;
            }
            else 
            {
                patten[i] = 0;
                len = 0;
            }
        }
    }
};

  

posted on 2014-03-21 13:25  pengyu2003  阅读(158)  评论(0编辑  收藏  举报

导航