leetcode Implement strStr()

2014-11-24 07:27:10 · 作者: · 浏览: 0

Implement strStr().

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

朴素匹配好像超时,只能改用kmp了。关于kmp算法就不多说了,是很经典的问题了,我只想补充一下,kmp有两种写法,有一个优化版本的。这两个版本不同之处在于求next数组的不同方法,我使用的是一般的next数组,next数组
就是保存最长前缀和后缀的匹配重度。

如果不理解kmp,搜下到处都有了,好久不看,自己推next推了很久才想起来。

class Solution {
public:

       void get_n(const char * pattern,int *p,int n)
        {
            p[0]=-1;
            for(int i=1;i
  
   =0&&pattern[j+1]!=pattern[i])
                    j=p[j];
                if(pattern[j+1]==pattern[i])
                    p[i]=j+1;
                else
                    p[i]=-1;
            }
        }
    char *strStr(char *haystack, char *needle) {
       if(!haystack||!needle)
        return NULL;
        int m=0,n=0;
        while(haystack[m])m++; 
        while(needle[n])n++;
        if(m
   
     如有不正之处请指正。