串的模式匹配(待完善)
#include <stdio.h>
#define MAXSIZE 100010
typedef struct {
char str[MAXSIZE];
int length;
}String;
void Init(String *S){
S->length = 0;
for (int i = 0; i < MAXSIZE; ++i) {
S->str[i] = '\0';
}
}
void Create(String *S){
printf("please enter the string:\n");
char ch='\0';
S->length = 0;
while (true){
scanf("%c",&ch);
if (ch == '\n')
break;
S->str[S->length] = ch;
S->length++;
}
}
void Print(String S){
for (int i = 0; i < S.length; ++i) {
printf("%c",S.str[i]);
}
printf("\n");
}
bool BF(const char s[],const char p[] ,int s_length,int p_length){
int i = 0, j = 0;
while (i<s_length && j<p_length){
if(s[i] == p[j]){
++i;
++j;
} else{
i = i-j+1;
j= 0;
}
}
if(j>=p_length)
return true;
else
return false;
}
void KMP(char s[], char p[], int s_length, int p_length){
int ne[p_length];
ne[0] = -1;
for (int i = 1, j = -1; i < p_length; ++i) {
while (j>=0 && p[j+1] != p[i])
j = ne[j];
if(p[j+1] == p[i])
j++;
ne[i] = j;
}
for (int i = 0, j = -1; i < s_length; ++i) {
while (j != -1 && s[i] != p[j+1])
j = ne[j];
if(s[i] == p[j+1])
j++;
if(j == p_length - 1){
printf("%d ", i - j);
j = ne[j];
}
}
}
int main(){
char str1[20]="ababacabcccdddac";
int str_1 = 16;
int str_2 = 2;
char str2[20]= "ac";
KMP(str1,str2,str_1,str_2);
return 0;
}