KMP算法
char str1[] = "abababcabb", str2[] = "ababc";
int len1 = strlen(str1), len2 = strlen(str2);
int next[len2];
next[0] = 0;
for (int i = 1; i< len2; i++) {
int j = i - 1;
while (1) {
if(next[j] == 0 || str1[j] == str2[next[j] -1]) {
next[i] = next[j] + 1;
break;
}
j = next[j] - 1;
}
}
int i = 0, j = 0;
while (i < len1) {
if(str1[i] == str2[j]) {
i++;
j++;
} else {
if(j == 0) {
i++;
} else {
j = next[j] - 1;
}
}
if(j == len2) break;
}
printf(j == len2 ? "匹配成功" : "匹配失败");
暴力匹配
char str1[] = "abcdabbc", str2[] = "cda";
int len1 = strlen(str1), len2 = strlen(str2);
_Bool flag = 0;
for (int i = 0; i < len1; i++) {
flag = 0;
for (int j = 0; j < len2; j++) {
if(str1[i + j] != str2[j]) {
flag = 1;
break;
}
}
if (!flag) break;
}
puts(flag ? "不包含" : "包含");