首页 > 代码库 > KMP字符串匹配

KMP字符串匹配

  1 #include<iostream>
  2 
  3 
  4 using namespace std;
  5 
  6 #define MAX    255
  7 
  8 typedef unsigned char BYTE;
  9 
 10 typedef BYTE String[MAX+1];
 11 
 12 bool strAssign(String& strTemp,char* Temp);   //定长字符串存储
 13 bool strTravel(String& strTemp);          //打印
 14 void KMP(String& strMother,String& strSon,int* pData);  
 15 void GetNext(String& strSon,int* pNext);
 16                                         //KMP算法的实现要求两个子函数  KMP()  和GetNext()
 17 
 18 void main()
 19 {
 20 
 21     String strMother;
 22     memset(strMother,0,sizeof(strMother));
 23 
 24     String strSon;
 25     memset(strSon,0,sizeof(strSon));
 26 
 27     strAssign(strMother,"HHHeHeHHe");
 28     strAssign(strSon,"HeHe");
 29 
 30 
 31     strTravel(strMother);
 32     strTravel(strSon);
 33     int* pData = http://www.mamicode.com/(int*)malloc(sizeof(int)*(strMother[0]+1));
 34 
 35     KMP(strMother,strSon,pData);
 36 
 37     int i = 0;
 38     for(i=1;i<=pData[0];i++)
 39     {
 40         cout<<pData[i]<<" ";
 41 
 42     }
 43     cout<<endl;
 44 
 45 }
 46 bool strAssign(String& strTemp,char* Temp)
 47 {
 48     strTemp[0] = strlen(Temp);
 49 
 50 
 51     int i = 1;
 52     for(i=1;i<=strTemp[0];i++)
 53     {
 54         strTemp[i] = Temp[i-1];
 55     
 56     }
 57 
 58     return true;
 59     
 60 }
 61 bool strTravel(String& strTemp)
 62 {
 63     int i = 1;
 64     for(i=1;i<=strTemp[0];i++)
 65     {
 66         cout<<strTemp[i]<<" ";
 67     
 68     }
 69 
 70     cout<<endl;
 71     return true;
 72 
 73 }
 74 void KMP(String& strMother,String& strSon,int* pData)
 75 {
 76     int* pNext = (int*)malloc(sizeof(int)*(strSon[0]+1));
 77     
 78     GetNext(strSon,pNext);
 79     
 80 
 81     int i = 1;
 82     int j = 1;
 83     int k = 1;
 84 
 85     while(i<=strMother[0])
 86     {
 87         if(i==0||strMother[i]==strSon[j])
 88         {
 89             i++;
 90             j++;
 91 
 92         }
 93         else
 94         {
 95             j = pNext[j];
 96         
 97         }
 98 
 99         if(j>strSon[0])
100         {
101             pData[k] = i-strSon[0];
102             k++;
103             j=1;
104         
105         }
106     
107     
108     }
109 
110 
111     pData[0] = k-1;
112     free(pNext);
113 
114 
115 }
116 void GetNext(String& strSon,int* pNext)
117 {
118     pNext[1] = 0;
119 
120     int i = 1;
121     int j = 0;
122 
123     while(i!=strSon[0])
124     {
125         if(j==0||strSon[i]==strSon[j])
126         {
127             i++;
128             j++;
129 
130             pNext[i] = j;
131         
132         
133         
134         }
135         else
136         {
137             j = pNext[j];
138         
139         }
140     
141     
142     }
143 }