KMP及next陣列實現程式碼
阿新 • • 發佈:2019-01-09
next陣列求解:
以1開始,next[1]=0,next[2]=1,next[n] :將前面n-1個字元,計算從首尾開始組成最大的相同子串的長度,如果找到,那麼next值是該長度加1,否則next值是1。
void getNext(char *p,int *next)
{
int j,k;
next[1]=0;
j=1;
k=0;
while(j<strlen(p)-1)
{
if(k==0||p[j]==p[k]) //匹配的情況下,p[j]==p[k],next[j+1]=k+1;
{
j++;
k++;
next [j]=k;
}
else //p[j]!=p[k],k=next[k]
k=next[k];
}
}
KMP實現:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int KMP(string S, string T)
{
vector<int> next = getNext(T);
int i = 1, j = 1;
while (S[i] != '\0' && T[j] != '\0')
{
if ( j==0 || S[i] == T[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (T[j] == '\0')
return i - j + 1;
else
return 0;
}
int main()
{
string S = "ababaababcb";
string T = "ababc";
int num = KMP(S, T);
cout << num;
return 0;
}