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

KMP算法

时间:2016-04-19 00:08:37      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

#include<cstdio>
#include<cstring>
#include<cstdlib>

void GetNext(char *t,int *next){
    int i =1,j = 0;
    next[0] = 0;
    while(i<t[0]){
        if(j == 0 || t[i] == t[j]){
            i++;
            j++;
            if(t[i]!=t[j]){
                next[i] = j;
            }else{
                next[i] = next[j];
            }
        }else{
            j = next[j];
        }
    }
}
int index_kmp(char *s,char *t,int pos){
    int i = pos;
    int j = 1;
    int next[88];
    
    GetNext(t,next);
    
    while(i < s[0] && j<=t[0]){
        if(0 == j||s[i] == t[j]){
            i++;
            j++;
        }else{
            j = next[j];
        }
    }
    if(j>t[0]){
        return i-t[0];
    }else{
        return 0;
    }
}
int main(){
    char t[88] = " aaaas";
    char s[88];
    t[0] = strlen(t)-1;
    while(~scanf("%s",s+1)){
        s[0] = strlen(s);
        printf(" %d\n",index_kmp(s,t,1));
    }
    return 0;
} 

 

KMP算法

标签:

原文地址:http://www.cnblogs.com/zhuozhuo/p/5406258.html

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