A brief explanation of BF algorithm (C++)

       The matching process of the BF algorithm is easy to understand. If there is a match, both the substring and the main string are shifted down one bit. When there is no match, the main string is traced back to the next digit of the starting index of this match. Example: In the third match in the figure, the main string does not match the substring when it reaches the seventh position. This time, the matching of the main string starts from the third position, so next time it starts from the fourth position (i-j+ 2=7-5+2=4).

#include<iostream>
#include<string>
using namespace std;
typedef struct node
{
	char ch[251];
	int length=0;//串当前长度
}SString;
int Index_BF(SString S, SString T, int pos)//S主串,T子串,pos从主串pos位置开始匹配
{
	int i = pos, j = 1;//i为主串下标,j为子串下标
	while (i <= S.length && j <= T.length)
	{
		if (S.ch[i] == T.ch[j])//匹配,往下继续
		{
			i++;
			j++;
		}
		else
		{
			i = i - j + 2;//不匹配,主串回溯至本次匹配开始下标的下一位
			j = 1;//子串重新开始
		}
	}
		if (j >= T.length) return i - T.length;//返回主串与子串匹配时,主串的第一个下标
		else return 0;
	
}
int main()
{
	SString  s;
	SString  t;
	cout << "输入主串长度:" ;
	cin >> s.length;
	cout << endl;
	cout << "输入子串长度:";
	cin >> t.length;
	cout << endl << "输入主串:";
	for (int i = 1; i <= s.length; i++)//从下标1开始储存
	{
		cin >> s.ch[i];
	}
	cout << endl << "输入子串:";
	for (int i = 1; i <= t.length; i++)
	{
		cin >> t.ch[i];
	}
	int a = Index_BF(s, t, 1);
	cout <<endl<< a;
}

Guess you like

Origin blog.csdn.net/qq_74156152/article/details/132921848