1.BF算法是什么?
BF算法,即两个字符串像物流传送带一般,主串固定,子串一步步像前移动,一位位匹配比较,直到完全匹配找到想要的结果的位置。
2.描述
BF算法的原理如下:
- 从主串text[i]和字串pattern[j]开始向后遍历。
- 若字符匹配,则索引向后移动。
- 否则,主串回退至第一个匹配的位置 + 1,子串回退至起始位置。
3.示例
/*
* 简单模式匹配
*/
char *_strstr(char *text, char *pattern) {
if (text == NULL) return NULL;
int tlength = strlen(text);
int plength = strlen(pattern);
int i = 0, j = 0;
while (i < tlength && j < plength) {
if (text[i] == pattern[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j == plength) {
return text + i - j;
}
return NULL;
}