初始化:定义2个数组 S为主串,T为子串,并静态设置长度。 一、设计BF算法 1.判断子串的长度是否为空、是否大于主串长度 2. 定义int i=0,j=0,pop=0(pop的作用在于每次返回S数组的位置);进行数组间的一一配对; 3.while循环 判断结束,i>主串长度或j>子串长度 结束 4.如果j>=子串长度,说明子串中的字符在主串中有一一配对的,则表明匹配成功,显示已感染病毒。否则显示:未感染病毒。 二、设计KMP算法 (一)Next函数 1.定义int j = 0, k = -1;next[0] = -1;核心是k的运算,我也不知道怎么想出来的,反正挺复杂。 2.通过判断 k == -1 || t[j] == t[k]来获取next数组中的值 判断成功:next[j] = k;重点,存入数组中 判断失败:k = next[k];返回 (二)KMP函数 与BF算法不同点是匹配失败,返回到next数组中对应的值。 1.定义与调用Next函数 int next[SIZE];int i = 0, j = 0; Next(t, next); 2.判断 j ==0 || s[i]==t[j],如果匹配成功,则j++,i++ 判断下一对字符,如果匹配失败T子串跳转到对应的next位置j = next[j]; 3.如果j>=子串长度,说明子串中的字符在主串中有一一配对的,则表明匹配成功,显示已感染病毒。否则显示:未感染病毒。 2.代码实现 #include<stdio.h> #include<string.h> #define MAXSIZE 20 #define SIZE 10 //BF算法 void BF(char*s ,char *t){ if(strlen(t)<1||strlen(t)>strlen(s)){ printf("长度有误!!"); return ; } int i=0,j=0,pop=0; while(i<strlen(s)&&j<strlen(t)){ if(s[i]==t[j]){ i++; j++; }else{ pop++; i=pop; j=0; } } if(j>=strlen(t)){ printf("已找到!!"); return; } else{ printf("未找到"); return; } } //获取next数组中的值 void Next(char *t, int next[]) { int j = 0, k = -1; next[0] = -1; while (j < strlen(t)) { if (k == -1 || t[j] == t[k]) { j++; k++; next[j] = k; } else { k = next[k]; } } } //KMP算法 void KMP(char* s, char* t) { int next[SIZE]; int i = 0, j = 0; Next(t, next); while (i < strlen(s) && j < strlen(t)) { if (j ==0 || s[i]==t[j]) { i++; j++; } else { j = next[j]; } } if (j >=strlen(t)) { printf("已找到!!\n"); return; } else { printf("未找到!!\n"); return ; } } int main(){ char S[MAXSIZE]; char T[SIZE]; printf("请输入主串:"); scanf("%s",S); printf("请输入匹配串:"); scanf("%s",T); KMP(S,T); BF(S,T); return 0;
|
}