#include <iostream>
#include <string>
using namespace std;
//普通模式匹配算法(BF)
int Index(string s1,string s2) {//s1为主串,s2为模式串
int i = 0, j = 0;
while (i < s1.size() && j < s2.size()) {
if (s1[i] == s2[j]) {
i++;
j++;
}
else {
i = i - j + 1;
j = 0;
}
}
if (i == s1.size()) {
return -1;
}
else {
//返回的位置从1开始
return i - s2.size() + 1;
}
}
int main()
{
string s1 = "aabbccddefg";
string s2 = "cdde";
if (Index(s1, s2) == -1)
cout << "不匹配" << endl;
else
cout << "匹配成功,在第" << Index(s1, s2) << "个位置" << endl;
}
数据结构——022串的模式匹配算法(BF)
最新推荐文章于 2021-12-15 12:16:15 发布