设有两个字符串s和t,首先将s1与t1进行比较,直到s的某一个字符si和ti相同,再将它们之后的字符进行比较,若也相同,则如此继续往下比较,当s的某一个字符si与t的字符tj不同时,则s返回到本趟开始字符的下一个字符,即si-j+2,t返回到t1,继续开始下一趟的比较,重复上述过程。若t中的字符全部比较完,则说明本趟匹配成功,本趟的起始位置是i-j+1,否则,匹配失败。
#include<stdio.h>
#include<iostream>
#include<string>
int BF_Index(std::string S, std::string T, int pos);
int KMP_Index(std::string S, std::string T, int pos);
void getNext(std::string S, int next[]);
static std::string getCorrectString() {
bool psw = false;
std::string intput, str;
do {
psw = false;
std::cin >> intput;
str = str + intput;
while (std::cin.peek() == ' ') { str = str + " "; std::cin.get(); psw = true; }
} while (psw);
return str;
}
int main() {
std::string SString, TString;
int pos;
std::cout << "请输入主字符串:";
bool psw = false;
SString = getCorrectString();
std::cout << std::endl;
std::cout << "请输入搜索串:";
TString = getCorrectString();
std::cout << std::endl;
std::cout << "请输入要检索的开始位置:";
std::cin >> pos;
std::cout << std::endl;
if (BF_Index(SString, TString, pos) != 0 && KMP_Index(SString, TString, pos) != 0) {
std::cout << "BF匹配成功开始位置是:第 " << BF_Index(SString, TString, pos) << " 个位置" << std::endl;
std::cout << "KMP匹配成功开始位置是:第 " << KMP_Index(SString, TString, pos) << " 个位置" << std::endl;
}
else
{
std::cout << "BF匹配失败" << std::endl;
std::cout << "KMP匹配失败" << std::endl;
}
return 0;
}
int BF_Index(std::string S, std::string T, int pos) {
int Slength = S.length();
int Tlength = T.length();
int i = pos - 1, j = 0;
while (i < Slength && j < Tlength)
{
if (S[i] == T[j]) {
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == Tlength)return i - Tlength + 1;
else
{
return 0;
}
}
int KMP_Index(std::string S, std::string T, int pos) {
int Slength = S.length();
int Tlength = T.length();
int i = pos - 1, j = 0;
int* next = (int*)malloc(sizeof(int) * (Tlength + 1));
getNext(T, next);
while (i < Slength && j < Tlength)
{
if (S[i] == T[j] || j == 0) {
i++; j++;
}
else
{
j = next[j];
}
}
if (j == Tlength)return i - Tlength + 1;
else
{
return 0;
}
}
void getNext(std::string T, int next[]) {
int j = 1, k = 0;
next[1] = 0;
while (j < T.length())
{
if (k == 0 || T[j] == T[k]) {
j++; k++; next[j] = k;
}
else {
k = next[k];
}
}
}