KMP 算法 && Implement strStr()

leetcode上的一道题:https://oj.leetcode.com/problems/implement-strstr/

实际上就是实现KMP算法,但是该算法我觉得算法导论讲的过于精简,理论证明过多导致初学者不容易搞懂,所以特别打印了csdn 人气博主 July(周磊)新书初稿KMP算法部分学习,发现他说的更加通熟易懂,而且是以例子来进行教学,比较容易接受。PDF下载地址:http://download.csdn.net/detail/huruzun/7819137

引用PDF中主体代码:

class Solution 
{
public:
    int getlen(char *str)
    {
        int i;
        for(i = 0; str[i] != '\0'; i ++)
            ;
        return i;
    }
    void getnext(char *str, int len, int next[])
    {
        int i = 0;
        next[i] = -1;
        int j = -1;

        while(i < len-1)
        {
            if(j==-1 || str[i]==str[j])
            {
                i++;
                j++;
                if(str[i] == str[j])
                    next[i] = next[j];
                else
                    next[i] = j;
            }
            else
                j = next[j];
        }
    }

    char *strStr(char *haystack, char *needle) 
    {
        int hlen = getlen(haystack);
        
        int nlen = getlen(needle);
        

        int *next = new int[nlen];
        getnext(needle, nlen, next);


        int i = 0;
        int j = 0;
        while(i != hlen && j != nlen)
        {
            if(j == -1 || haystack[i] == needle[j])
            {
                i++;
                j++;
            }
            else
            {
                j = next[j];
            }
        }
        if(j == nlen)
            return &haystack[i-nlen];
        else
            return NULL;
    }
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值