首页 > 编程语言 > 详细

KMP算法

时间:2016-08-30 00:29:09      阅读:279      评论:0      收藏:0      [点我收藏+]

                     

/*
 * main.cpp
 *
 *  Created on: 2016年8月29日
 *      Author: godsome
 */
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int next[100];
int Index_KMP(char s[], char t[]){
    int len_s = strlen(s), len_t = strlen(t);
    int i = 0, j = 0;
    while(i < len_s && j < len_t){
        if(s[i] == t[j]){
            i++;
            j++;
        }
        else if(j == 0)
            i++;
        else
            j = next[j-1] + 1;
    }
    if(j == len_t) return i - len_t;
    else return -1;
}

void get_next(char str[], int next[]){
    int len = strlen(str);
    int i, j;
    next[0] = -1;
    for(i = 1; i < len; i++){
        j = next[i-1];
        while(str[j+1]!=str[i] && j>=0)
            j = next[j];
        if(str[i] == str[j+1])
            next[i] = j + 1;
        else
            next[i] = -1;
    }
}

int main(){
    char *p = "ababcabcacbab";
    char *t = "abcac";
    get_next(t, next);
    int pos = Index_KMP(p, t);
    printf("%d\n", pos);
    return 0;
}

 

KMP算法

原文:http://www.cnblogs.com/yingl/p/5820138.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!