字符串的比较
发布日期:2021-05-15 01:18:34 浏览次数:20 分类:精选文章

本文共 2020 字,大约阅读时间需要 6 分钟。

BF算法与KMP算法实现分析

BF算法是一种寻找子串的算法,与KMP算法相比,它采用“回退”技术处理不匹配情况。本文将完整阐述两种算法的实现思路和代码细节。

前置代码:

#include 
#include
#include
int main(void) {
char *str1, *str2;
int base = 0, A1 = 0, A2 = 0, Len1, Len2;
bool flag = 0;
str1 = (char*)malloc(100 * sizeof(char));
str2 = (char*)malloc(100 * sizeof(char));
printf("母串为:");
scanf("%s", str1);
printf("子串为:");
scanf("%s", str2);
Len1 = strlen(str1);
Len2 = strlen(str2);
printf("母串长度为:%d, 子串长度为:%d\n", Len1, Len2);
while ((Len1 - A1) > 0 && (Len2 - A2) > 0) {
flag = 0;
if (str1[A1] == str2[A2]) {
A1++;
A2++;
} else {
base++;
A1 = A1 - A2 + 1;
A2 = 0;
flag = 1;
}
}
if (flag) {
printf("\n非子串\n");
} else {
printf("\n是子串,从第%d位开始相等\n", base);
}
return 0;
}

KMP算法代码解释:

#include 
#include
#include
#include
#include
#include
typedef char* string; int IndexKmp(string s, string t, int pos); void GetNext(string T, int* next); int main(void) { char str_0[10] = "abcdefg"; char str_1[5] = "abcd"; str_0[0] = 'g'; str_1[0] = 'e'; int result = 0; result = IndexKmp(str_0, str_1, 1); printf("%d\n", result); return 0; } int IndexKmp(string s, string t, int pos) { int i = pos; int j = 1; int next[255]; GetNext(t, next); while (i <= s[0] && j <= t[0]) { if (s[i] == t[j] || j == 0) { i++; j++; } else { j = next[j]; } } if (j > t[0]) { return i - t[0]; } else { return -1; } } void GetNext(string T, int* next) { int j = 0; int i = 1; next[1] = 0; while (i < T[0]) { if (0 == j || T[i] == T[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } }

BF算法主要思想是逐步比较母串和子串的字符,当不匹配时,采用回退方式将子串头部调整到前一个匹配位置。这种方法避免了从头开始比较多次带来的低效问题。

KMP算法则通过预处理母串,创建一个“下一个”数组来记录每个子串位置对应的下一个匹配位置,从而实现高效的字符串匹配。两种算法在处理大规模文本时都能显著提升性能。

实用建议:在实际应用中,可以根据具体需求选择更高效的算法。在处理文本较长时,KMP算法的预处理时间稍长,但匹配速度更快;而BF算法则在处理短文本时更为效率。

上一篇:树型结构
下一篇:递归与分治

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月30日 07时54分26秒