KMP匹配算法对我来说很复杂。
目前只是有一些了解。
2013.6.10
KMP算法远没有想象中那么难。
要理解KMP算法,只需要理解这个就行了。以abaabcac为例
j 1 2 3 4 5 6 7 8
--------------------------
模式串 a b a a b c a c
next[j] 0 1 1 2 2 3 1 2
设next[j] = k, 这表明在模式串中存在下列关系
'p1......pk-1' = 'pj-k+1.......pj-1'
void get_next(SString T, int next[]){
i = 1; next[1] = 0; j = 0;
while (i < T[0]) {
if(j == 0||T[i] == T[j]) { ++i; ++j; next[i] = j;}
else j = next[j];
}
}
2013.7.3
#include <iostream>
static const int MaxSize = 100;
using namespace std;
void GenKMPNext (int Next[], char C_My_String[] , int len_mystring)
{
int i = 0, j = -1;
Next[0] = -1;
while (i < len_mystring)
{
while(j >= 0 && C_My_String[i] != C_My_String[j])
j = Next[j];
i++; j++;
if(C_My_String[i] == C_My_String[j])
Next[i] = Next[j];
else Next[i] = j;
}
}
int Find (char C_String[], char My_String[] ,int len_of_string, int len_of_mystring )
{
int i, j, next[MaxSize];
GenKMPNext(next, My_String, len_of_mystring);
for(i = 0,j = 0; i < len_of_mystring && j < len_of_string;)
{
if(My_String[i] == C_String[j])
{i++; j++;}
else if (next[i] >= 0)
i = next[i];
else
{i = 0; j++;}
}
if (i >= len_of_mystring)
return j - len_of_mystring;
else
return -1;
}
void main()
{
char String[MaxSize];
char MyString [MaxSize];
int next[MaxSize];
int string_length; //储存字符串长度
int my_string_length; //储存子串长度
cout << "请输入子串" << endl;
scanf ("%s", &*MyString);
cout << "请输入字符串" << endl;
scanf ("%s", &*String);
for( string_length = 0; String[string_length] !='\0'; string_length ++)
; //string_length 储存字符串长度
for( my_string_length = 0; MyString[my_string_length] !='\0'; my_string_length ++)
; //my_string_length 储存zi串长度
int where = Find (String, MyString, string_length, my_string_length);
cout << where+1 << endl;
}