zoukankan      html  css  js  c++  java
  • KMP字符串模式匹配算法

    原理就不说了,学算法的都知道这基本上是查找一个字符串是否在另一个串中位置比较快的算法。代码如下:
    [cpp]  
    #include <stdio.h>  
    #include <string.h>  
    #define MAXSIZE 100  
    int next[MAXSIZE];  
    int S_lenth,D_lenth;  
    char source[MAXSIZE],detination[100];  
    void get_next()  
    {  
        int i=1,j=0;  
        next[1]=0;  
        while(i<=D_lenth)  
        {  
            if(j==0||(detination[i-1]==detination[j-1]))  
            {  
                ++i;  
                ++j;  
                next[i]=j;  
            }  
            else  
            {  
                j=next[j];  
            }  
        }  
    }  
    int KMP()  
    {  
        int i=0,j=1;  
        while(i<=S_lenth&&j<=D_lenth)  
        {  
            if(j==0||(source[i]==detination[j-1]))  
            {  
                ++i;  
                ++j;  
            }  
            else  
            {  
                j = next[j];  
            }  
        }  
        if(j>D_lenth)  
        {  
            return i-D_lenth;  
        }  
        else  
            return 0;  
    }  
    int main()  
    {  
        int i=0;  
        printf("输入源串!!!\n");  
        scanf("%s",&source);  
        printf("输入模式串!!!\n");  
        scanf("%s",&detination);  
        S_lenth = strlen(source);  
        D_lenth = strlen(detination);  
        get_next();  
        printf("next数组元素为:\n");  
        for(i=1;i<=D_lenth;i++)  
        {  
            printf("%d ",next[i]);  
        }  
        printf("\n模式串开始于源串%d位置处",KMP());  
        return 0;  
    }  
  • 相关阅读:
    在rhel上配置yum 源
    python2.7 使用生成器方式实现斐波那契数列
    Web 应用程序测试思考
    python2.7 可迭代对象、迭代器和迭代的概念说明
    python2.7 zipfile 的简单用法
    python函数定义中的参数说明
    python 内置函数filter、map、reduce的使用说明
    python虚拟环境迁移
    python yaml 文件解析及str、repr函数的说明
    python xlrd、xlwt、xlutils操作excel文件
  • 原文地址:https://www.cnblogs.com/jinsedemaitian/p/5589203.html
Copyright © 2011-2022 走看看