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]!='\0')&&(T[j]!='\0'))
 {
  if (S[i]==T[j])
  {
   i++;
   j++;
  }
  else
  {
   index++;
   i = index;
   j = 0;
  }
 }
 if (T[j] == '\0')
  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;
}

 

posted @ 2016-02-26 13:40  白衣秀才  阅读(156)  评论(0编辑  收藏  举报