#include<iostream>
using namespace std;
bool _Get_Nextvalue(char c_pattern_string[], int i_next_value[])
{
int length = strlen(c_pattern_string);
if (!c_pattern_string || !length)
return false;
i_next_value[ 0 ] = 0;
int j = -1, i = 0;
length--;
while (i < length)
{
if (j == -1 || c_pattern_string[ i ] == c_pattern_string[ j ])
if (c_pattern_string[ ++i ] == c_pattern_string[ ++j ])
i_next_value[i] = i_next_value[j];
else
++(i_next_value[i] = j);
else
--(j = i_next_value[j]);
}//while
return true;
}
int Index_KMP(char c_sourse_string[], char c_pattern[], int i_next_value[], int start_pos, int length_pattern)
{
//c_sourse_string[]源串 c_pattern[]模式字符串
int i = start_pos, j = 0, length = strlen(c_sourse_string);
while (i < length && j < length_pattern)
{
if (j == -1 || c_sourse_string[ i ] == c_pattern[ j ])
{
i++;
j++;
}
else
--(j = i_next_value[j]);
}
if (j >= length_pattern)
return i - length_pattern;
else
return -1;
}
int main(void)
{
char c_pattern_string1[] = "abaaasssaaaadfghaaaaa", c_pattern_string[] = "aaaaa";
int length_str = strlen(c_pattern_string);
int * i_next_value = new int [ length_str];
_Get_Nextvalue(c_pattern_string, i_next_value);
int i = Index_KMP(c_pattern_string1, c_pattern_string, i_next_value, 0, length_str);
if (i != -1)
for (length_str = strlen(c_pattern_string1) ;i < length_str; i++)
cout << c_pattern_string1[ i ] << " ";
cout << endl;
delete i_next_value;
i_next_value = NULL;
return 0;
}