zoukankan      html  css  js  c++  java
  • 重装 代码备忘 之kmp

    image

    // kmp.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"

    #include "stdio.h"
    #include<iostream>
    #include<string>
    using namespace std;

        //int * myComputePrefix(string);
    int * myComputePrefix( string& P)
    {
        int m=P.size();
        int *PI=new int[20];
        PI[1]=0; //NOT USE 1
        int k=0;
        int q,ii;
                for(ii=0;ii<20;ii++) PI[ii]=-1;//init by 66

                for(q=2;q<m;q++)//66 from second to last
                {
                            //这个while每次要么不执行,PI[q]=-1;要么执行一次。
                    while(k>=0 && P[k+1]!= P[q])
                        k=PI[k];

                if (P[k+1] == P[q])        //hence here ,use P[]
                    k=k+1;        //这句有两句的含义。品味
                PI[q]=k;        //是不是要不是 成功找到的上面那种,或者-1;

                //for debug
                printf("ovevlay %d : %d \n",q,PI[q]);
            }
            return PI;
    }

    void myKmpMatch(string &T,string & P)
    {
    int n=T.size();
    int m=P.size();
    int *PI=new int[20];

    PI=myComputePrefix(P);

    //debug check;
    int i;
                for ( i=0;i<m;i++)    //BUG ..P.size > PI....
                printf("check ovevlay %d : %d \n",i,PI[i]);

    int q=-1;  //Number of characters matched. 66 we set -1
             //    for(int i;;i++)...  ; for(int i=0;;)没有受影响?

    for(i=0; i<n;i++)
    {
            //第一个字幕比较,就不经过这里就是。而且全部都不经过?//66
            //q >0 在 第一个字母 不等起作用啦。
        while(q>0 && P[q+1] != T[i])
        {
            q=PI[q];        //why?
        }
            //想像一下,-1+1也会从这里过啊。
        if ( P[q+1] == T[i])
            q=q+1;          //相当于 两个游标 动

        if (q ==m -1) //66
            {
                printf("index %d patch ok \n", i);
                q=PI[q];   
            }
    }

    }

    int _tmain(int argc, _TCHAR* argv[])
    {
            string T="bababa";//

        //string P="abaabc";
                    //string P="ababababca";
                            //string P="aabaa";
            string P="aba";

    //dw :char *x=[];只能一次赋值? String 是 只有一次?
            //printf("Target : %s  ,Pattern %s \n",T,P);

        myKmpMatch(T,P);
        printf("game ok\n");
        getchar();
        return 0;
    }

  • 相关阅读:
    ntopng网络流量实时监控
    LVS初始使用步骤
    Pycharm快捷方式
    Python之路,Day9, 进程、线程、协程篇
    Python之路,Day7
    Python 之路 Day5
    Python之路,Day6
    Python之路,Day3
    Python之路,Day2
    Python之路,Day1
  • 原文地址:https://www.cnblogs.com/titer1/p/2316001.html
Copyright © 2011-2022 走看看