• KMP算法求解


    // KMP.cpp : 定义控制台应用程序的入口点。
    //
    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    int BF(char S[], char T[])
    {
     int i=0, j=0;
     int index = 0;
     while ((S[i]!='')&&(T[j]!=''))
     {
      if (S[i]==T[j])
      {
       i++;
       j++;
      }
      else
      {
       index++;
       i = index;
       j = 0;
      }
     }
     if (T[j] == '')
      return index + 1;
     else
     {
      return 0;
     }
    }
    void getNext(char *p, int *next)
    {
     int j, k;
     next[0] = -1;
     j = 0;
     k = -1;
     while (j<strlen(p) - 1)
     {
      if (k == -1 || p[j] == p[k])    //匹配的情况下,p[j]==p[k]
      {
       j++;
       k++;
       next[j] = k;
      }
      else                   //p[j]!=p[k]
       k = next[k];
     }
    }
    int KMPMatch(char *s, char *p)
    {
     int next[100];
     int i, j;
     i = 0;
     j = 0;
     getNext(p, next);
     while (i<strlen(s))
     {
      if (j == -1 || s[i] == p[j])
      {
       i++;
       j++;
      }
      else
      {
       j = next[j];       //消除了指针i的回溯
      }
      if (j == strlen(p))
       return i - strlen(p);
     }
     return -1;
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
     char *a;
     char *b;
     char arr0[] = "abcde";
        char arr1[] = "cd";
     a = arr0;
     b = arr1;
     cout<<"比较相等的起始值为:"<<KMPMatch(a, b);
     return 0;
    }

     

  • 相关阅读:
    java自带线程池
    SQL 语句学习
    Eclipse 运行内存不足情况
    Eclipse的ant调用maven
    Elipse 无法启动问题(转)
    UI自动化测试实战之Select类实战(四)
    WebElement类方法实战(三)
    WebDriver浏览器属性详解(二)
    服务端测试之gRPC协议测试(一)
    服务端测试实战(一)
  • 原文地址:https://www.cnblogs.com/penglei-it/p/5220148.html
Copyright © 2020-2023  润新知