[Leetcode] 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做了。推荐不熟悉KMP的童鞋看这篇帖子:http://www.matrix67.com/blog/archives/115 (关于算法的解释和复杂度的解释都很明了)

Pattern数组的生成其实本身就是一种KMP,是needle的“自我匹配”。所以其实只要把kmp函数的算法记住就行了。

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(haystack==NULL||needle==NULL) return NULL;
        int nlen = strlen(needle);
        int hlen = strlen(haystack);
        if(nlen==0) return haystack;
        if(hlen==0) return NULL;
        vector<int> pattern(nlen);
        generatePattern(needle,pattern);
        return kmp(haystack,needle,pattern);        
        
    }
    
    void generatePattern(char* str, vector<int> &pattern)
    {
        pattern[0] = -1;
        int k = -1;
        for(int i=1;i<pattern.size();i++)
        {
            while(k>-1 && str[k+1]!=str[i])
            {
                k = pattern[k];
            }
            if(str[k+1]==str[i])
            {
                k++;
            }
            pattern[i] = k;            
        }
    }
    
    char *kmp(char* haystack, char* needle, vector<int> &pattern)
    {
        int k = -1;
        int hlen = strlen(haystack);
        int nlen = strlen(needle);
        for(int i=0;i<hlen;i++,haystack++)
        {
            while(k>-1 && needle[k+1]!= *haystack)
            {
                k = pattern[k];
            }
            if(needle[k+1]==*haystack)
            {
                k++;
            }
            if(k==nlen-1)
            {
                return haystack-k;
            }
        }
        return NULL;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值