5.2.1 普通算法
程序代码:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSIZE 100 int mate(char* P, char* T) { int i = 0, j = 0; while (i < strlen(P) && j < strlen(T)) { if (P[i] == T[j]) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j == strlen(T)) { return i - strlen(T) + 1; } return -1; } int main() { char* P=(char*)malloc(sizeof(char)*MAXSIZE); char* T=(char*)malloc(sizeof(char)*MAXSIZE); printf("请输入目标T:\n"); scanf("%s", T); printf("请输入模式P:\n"); scanf("%s", P); int number = mate(T, P); printf("%d", number); return 0; } |
运行截图:
5.2.2 KMP算法
程序代码:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSIZE 100 void Next(char* T, int* next) { int i = 1; next[1] = 0; int j = 0; while (i < strlen(T)) { if (j == 0 || T[i - 1] == T[j - 1]) { i++; j++; next[i] = j; } else { j = next[j]; } } } int KMP(char* S, char* T) { int next[10]; Next(T, next); int i = 1; int j = 1; while (i <= strlen(S) && j <= strlen(T)) { if (j == 0 || S[i - 1] == T[j - 1]) { i++; j++; } else { j = next[j]; } } if (j > strlen(T)) { return i - (int)strlen(T); } return -1; } int main() { char* P = (char*)malloc(sizeof(char) * MAXSIZE); char* T = (char*)malloc(sizeof(char) * MAXSIZE); printf("请输入目标T:\n"); scanf("%s", T); printf("请输入模式P:\n"); scanf("%s", P); printf("返回位置:"); int i = KMP(T, P); printf("%d", i); return 0; } |
运行截图: