KMP 算法

分析:spa

//先佔個坑,有閒時再來補上code

實現:blog

#include <string.h>
#include <malloc.h>
#include <stdio.h>

#define ERROR 0
#define OVERFLOW -2

int *get_nextval(char *s)
{
    int i, j;
    int *nextval;
    if (!(nextval = (int*)malloc(strlen(s) * sizeof(int))))
        exit(OVERFLOW);
    i = 0;
    j = -1;
    nextval[0] = -1;
    while (i < strlen(s))
    {
        if (j == -1 || s[i] == s[j])
        {
            i++;
            j++;
            if (s[i] == s[j])
                nextval[i] = nextval[j];
            else
                nextval[i] = j;
        }
        else
            j = nextval[j];
    }
    return nextval;
}

int  Index(char *s, char *t, int pos)
{
    int i, j, lens, lent, *nextval;
    if (pos < 0)
    {
        exit(ERROR);
    }
    lens = strlen(s);
    lent = strlen(t);
    nextval = get_nextval(t);
    i = pos;
    j = 0;
    while (i < lens && j < lent)
    {
        if (s[i] == t[j] || j == -1)
        {
            i++;
            j++;
        }
        else
            j = nextval[j];
    }
    if (j >= lent)
        return i - lent;
    else 
        return -1;
}

int main()
{
    char s[20] = "abcaacabcac";
    int i, j;
    for (i = 0; i < strlen(s); i++)
    {
        if (-1 == (j = Index(s, "abc", i)))
            break;
        else
            printf("%d\n", j);
            i = j + strlen("abc") - 1;
    }
    return 0;
}
相關文章
相關標籤/搜索