KMP算法复习

g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2下编译和运行通过


#include<iostream>
#include<string.h>
using namespace std;

int * getnext(char* substr)
{
    unsigned int i = 0;
    int j = -1;
    int n = strlen(substr);
    int *next = new int(n);
    next[0] = -1;
    while (i < strlen(substr))
    {
        if (j == -1 || substr[i] == substr[j]) {
            ++i;
            ++j;
            next[i] = j;

        }
        else {
            j = next[j];
        }
    }
    return next;
}


int KMP(char* str, char* substr)
{
    int unsigned i = 0, j = 0;
    int *next;
    next = getnext(substr);

    while (i < strlen(str) && j < strlen(substr))
    {
        if (str[i] == substr[j])
        {
            ++i;
            ++j;
        }
        else
        {
            j = next[j];
            if (j == -1)
            {
                j = 0;
                ++i;
            }

        }
    }
    if (j == strlen(substr))
        return (i - strlen(substr));
    else
        return 0;
}
int main()
{
    char* str = "abababc";
    char* substr = "abc";
    int i = KMP(str, substr);
    cout << "This is the result:" << endl;
    cout << i << endl;//result = 4
    return 0;
}

我在牛客网上implement str的解答:(不知道为什么通不过测试,请指教!)

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        int i = 0;
        int j = 0;
        int m = strlen(haystack);
        int n = strlen(needle);
        int *next = new int[n];
        getnext(needle, next);
        while (i < m && j < n)
        {
            if (j == -1 || haystack[i] == needle[j])
            {
                ++i;
                ++j;
            }
            else
            {
                j = next[j];
            }
        }
        if (j >= n)
            return (i - j);
        else
            return -1;
    }

    void getnext(char *needle, int next[])
    {
        int i = 0, j = -1;
        int n = strlen(needle);
        next[0] = -1;
        while (i <n) {
            if (j == -1 || needle[i] == needle[j])
            {
                ++i;
                ++j;
                next[i] = j;
            } 
            else
                j = next[j];
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值