加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

克努特 - 莫里斯 - 普拉特算法的C语言实现

发布时间:2020-12-16 07:43:26 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 /* Copyright 2011 Shao-Chuan Wang shaochuan.wang AT gmail.com Permission is hereby granted,free of charge,to any person obtaining a copy of

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

/*
   Copyright 2011 Shao-Chuan Wang <shaochuan.wang AT gmail.com>
 
    Permission is hereby granted,free of charge,to any person obtaining a copy
    of this software and associated documentation files (the "Software"),to deal
    in the Software without restriction,including without limitation the rights
    to use,copy,modify,merge,publish,distribute,sublicense,and/or sell
    copies of the Software,and to permit persons to whom the Software is
    furnished to do so,subject to the following conditions:
 
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
 
    THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR
    IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER
    LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int *compute_prefix_function(char *pattern,int psize)
{
    int k = -1;
    int i = 1;
    int *pi = malloc(sizeof(int)*psize);
    if (!pi)
        return NULL;
 
    pi[0] = k;
    for (i = 1; i < psize; i++) {
        while (k > -1 && pattern[k+1] != pattern[i])
            k = pi[k];
        if (pattern[i] == pattern[k+1])
            k++;
        pi[i] = k;
    }
    return pi;
}
 
int kmp(char *target,int tsize,char *pattern,int psize)
{
    int i;
    int *pi = compute_prefix_function(pattern,psize);
    int k = -1;
    if (!pi)
        return -1;
    for (i = 0; i < tsize; i++) {
        while (k > -1 && pattern[k+1] != target[i])
            k = pi[k];
        if (target[i] == pattern[k+1])
            k++;
        if (k == psize - 1) {
            free(pi);
            return i-k;
        }
    }
    free(pi);
    return -1;
}
 
int main(int argc,const char *argv[])
{
    char target[] = "ABC ABCDAB ABCDABCDABDE";
    char *ch = target;
    char pattern[] = "ABCDABD";
    int i;
 
    i = kmp(target,strlen(target),pattern,strlen(pattern));
    if (i >= 0)
        printf("matched @: %sn",ch + i);
    return 0;
}
/** end of http://code.activestate.com/recipes/577908/ }}} */

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读