码迷,mamicode.com
首页 > 编程语言 > 详细

KMP 算法

时间:2015-03-30 21:13:03      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:kmp

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
const int MAX = 100;
int nextVal[MAX];

void get_next(char t[]){
    int len = strlen(t);
    int i=1;
    int j=0;
    nextVal[1]=0;
    while(i < len){
        if(j==0 || t[i]==t[j]){
            i++;
            j++;
            if(t[i]!=t[j])
                nextVal[i] = j;
            else
                nextVal[i] = nextVal[j];
        }
        else
            j = nextVal[j];
    }
}
int KMP(char s[],char t[]){
    int len_s = strlen(s);
    int len_t = strlen(t);
    int i,j;
    i = 0;
    j = 0;
    while(i<len_s && j<len_t){
        if(s[i] == t[j]){
            i++;
            j++;
        }else{
            j = nextVal[j];
            i++;
        }
        if(j == len_t)
            break;
    }
    if(j == len_t)
        return i-j;
    else
        return -1;
}

int main()
{
    char s[] = {'a','b','a','b','c','a','b','d','\0'};
    //char t[] = {'a','b','a','b','c','a','b','d','\0'};
    char t[] = {'b','a','\0'};
    int kmp;
    get_next(t);

    kmp = KMP(s,t);
    cout<<kmp<<endl;
    cout << "Hello world!" << endl;
    return 0;
}

KMP 算法

标签:kmp

原文地址:http://blog.csdn.net/xd_122/article/details/44756109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!