算法 || 蛮力法【字符串匹配问题】#04

字符串匹配问题

问题描述
对于字符串s和t,若t是s的子串,返回t在s中的位置(t的首字符在s中对应的下标),否则返回-1
问题求解
采用暴力法穷举求解,从s的每一个字符开始查找,看t是否会出现。当比较的两个字符不相同时,回退 i,j,重新查找。
代码

//字符串匹配
//对于字符串s和t,若t是s的子串,返回t在s中的位置(t的首字符在s中对应的下标),否则返回-1
#include<iostream>
#include<string> 
using namespace std;

int BF(const string& s, const string& t)
{
    
    
	int i = 0, j = 0;
	while (i < s.length() && j < t.length())
	{
    
    
		//当两个字符相同时
		if (s[i] == t[j])
		{
    
    
			i++, j++;
		}
		else
		{
    
    
			i = i - j + 1;//i回退
			j = 0;
		}
	}
	if (j == t.length())
		return i - j;
	else
		return -1;
}
int main()
{
    
    
	string s, t;
	cout << "请输入第一个字符串 s:";
	cin >> s;
	cout << "请输入第二个字符串 t:";
	cin >> t;
	cout << BF(s, t) << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43759081/article/details/121953951