问题描述:
分别输入字符串1和字符串2,若在字符串1中匹配到字符串2,则输出匹配位置。
(1)BF算法
代码展示:
#include "pch.h"
#include <iostream>
#include <String>
using namespace std;
#define MaxSize 100
typedef struct
{
char data[MaxSize];
int length;
}SqString;
int BF(SqString s,SqString t)
{
int i = 0, j = 0;
while (i<s.length&&j<t.length)
{
if (s.data[i]==t.data[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j >= t.length)
return i - t.length;
else
{
return -1;
}
}
int main()
{
SqString sqstring1,sqstring2;
string str1, str2;
cout << "BF算法\n请输入字符串1:";
cin >> str1;
cout << "请输入字符串2:";
cin >> str2;
sqstring1.length = str1.length();
sqstring2.length = str2.length();
strcpy_s(sqstring1.data,str1.c_str());
strcpy_s(sqstring2.data,str2.c_str());
int x=BF(sqstring1,sqstring2);//接收返回值,判断
if (x == -1)
{
cout << "未在字符串1中匹配到字符串2!" << endl;
}
else
{
cout << "字符串2在字符串1中的位置是:" << x+1 << endl;//+1输出真实坐标
}
return 0;
}
运行结果:
(2)KMP算法
代码展示:
#include "pch.h"
#include <iostream>
#include <String>
using namespace std;
#define MaxSize 100
typedef struct
{
char data[MaxSize];
int length;
}SqString;
void GetNextval(SqString t,int nextval[])//由模式串t求出nextval值
{
int j = 0, k = -1;
nextval[0] = -1;
while (j < t.length)
{
if (k == -1 || t.data[j] == t.data[k])
{
j++;
k++;
if (t.data[j] != t.data[k])
nextval[j] = k;
else
nextval[j] = nextval[k];
}
else
{
k = nextval[k];
}
}
}
int KMPIndexl(SqString s, SqString t)
{
int nextval[MaxSize], i = 0, j = 0;
GetNextval(t, nextval);
while (i < s.length&&j < t.length)
{
if (j == -1 | s.data[i] == t.data[j])
{
j++;
i++;
}
else
j = nextval[j];
}
if (j >= t.length)
return i - t.length;
else
return -1;
}
int main()
{
SqString sqstring1, sqstring2;
string str1, str2;
cout << "KMP算法\n请输入字符串1:";
cin >> str1;
cout << "请输入字符串2:";
cin >> str2;
sqstring1.length = str1.length();
sqstring2.length = str2.length();
strcpy_s(sqstring1.data, str1.c_str());
strcpy_s(sqstring2.data, str2.c_str());
int x = KMPIndexl(sqstring1, sqstring2);//接收返回值,判断
if (x == -1)
{
cout << "未在字符串1中匹配到字符串2!" << endl;
}
else
{
cout << "字符串2在字符串1中的位置是:" << x + 1 << endl;//+1输出真实坐标
}
return 0;
}
运行结果: