zoukankan      html  css  js  c++  java
  • KMP算法实现

    依照KMP实现的算法,附带测试用例。

    #include <algorithm>
    #include
    <iostream>
    #include
    <iterator>
    #include
    <string>
    #include
    <vector>
    #include
    <cassert>
    #include
    <cstring>
    using namespace std;


    /**计算next***/
    void kmp_next(char *pattern,int *next)
    {
    int i = 0 ;
    int j = next[0] = -1;
    while(pattern[i]!= '\0')
    {
    if((j == -1) || (pattern[i] == pattern[j]))
    next[
    ++i]= ++j;
    else
    j
    = next[j];
    }
    }
    /**计算next_val***/
    void kmp_next_val(char *pattern,int *next_val)
    {
    int i = 0;
    int j = next_val[0] = -1;
    while(pattern[i]!='\0')
    {
    if((j == -1)|| (pattern[i] == pattern[j]))
    if(pattern[++i] != pattern[++j])
    next_val[i]
    = j;
    else
    next_val[i]
    = next_val[j];
    else
    j
    = next_val[j];
    }
    }
    /****match 是长串**

    *****pattern 是模式串*
    */
    int kmp_match(char *match,char *pattern)
    {
    int m = strlen(pattern);

    int next[m];
    int i,j;
    /**打印表格**/
    for(i = 0; i < m ; ++i)
    cout
    <<i<<'\t';
    cout
    <<endl;
    kmp_next(pattern,next);
    copy(next,next
    +m,ostream_iterator<int > (cout,"\t"));
    cout
    <<endl;
    kmp_next_val(pattern,next);
    copy(next,next
    +m,ostream_iterator<int > (cout,"\t"));
    cout
    <<endl;

    i
    = j = 0;
    while((match[i]!='\0')&&(pattern[j]!='\0'))
    {
    if((j == -1)||(match[i] == pattern[j]))
    ++i,++j;
    else
    j
    = next[j];

    }
    return j == m?(i -j):-1;
    }


    int main(int argc,char *argv[])
    {
    char src[max_size];
    char dst[max_size];
    int m ,n;
    int position = 0;
    while(cin >> src >> dst)
    {
    position
    = kmp_match(src,dst);

    if(position != -1)
    cout
    <<"find at \t "<<position<<endl;
    else
    cout
    <<"not a substring\n";

    cout
    <<"--------end----------\n\n";
    }
    return 0;
    }


  • 相关阅读:
    jQuery制作焦点图(轮播图)
    mysql 存储引擎的选择
    linux 系统操作
    把网页转换成doc 格式的文件,方便用户下载PHP 方法
    多年级勾选
    zend studio 破解
    win7下安装Linux实现双系统全攻略
    【Linux】Linux中常用操作命令
    PHP xmapp 下面安装 Composer-Setup.exe
    ecshop中smarty比较操作符(eq,ne,neq)含义
  • 原文地址:https://www.cnblogs.com/westfly/p/kmp_algorithm.html
Copyright © 2011-2022 走看看