赞
踩
- #include <iostream>
- using namespace std;
- int * computePrefixFunction(const char * P)
- {
- int k = 0;
- int length = strlen(P);
- int * pi = (int *)new int[length+1];
- pi[1] = 0;
- int i;
- for(i=2;i<=length;i++)
- {
- while(k>0 && P[i-1] != P[k])
- k = pi[k];
- if(P[k] == P[i-1])
- k = k+1;
- pi[i] = k;
- }
- return pi;
- }
- void KMPFunction(const char * T,const char * P)
- {
- int * pi = computePrefixFunction(P);
- int lengthOfText = strlen(T);
- int lengthOfPattern = strlen(P);
- int i;
- int q = 0;
- for(i=1;i<=lengthOfText;i++)
- {
- while(q>0 && T[i-1] != P[q])
- q = pi[q];
- if(T[i-1] == P[q])
- q = q+1;
- if(q == lengthOfPattern)
- {
- cout<<"匹配位置"<<i-lengthOfPattern<<endl;
- q = pi[q];
- }
- }
- }
- void main ()
- {
- char * T = "abcbabababacagggabababaababaca";
- char * P = "ababaca";
- KMPFunction(T,P);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。