我一直在研究这种 Morris-Pratt 算法以将子字符串与文本匹配,但我在如何在实际函数中声明失败函数以使编译器不会抱怨时遇到了麻烦。我有 2 个小时的时间来完成这个。所以请尽快帮助我:/
int KMPmatch(const string& text, const string& pattern)
{
int n = text.size();
int m = pattern.size();
std::vector<int> fail = computeFailFunction(pattern);
int i = 0;
int j = 0;
while (i < n)
{
if (pattern[j] == text[i])
{
if (j == m-1) return i-m+1;
i++; j++;
}
else if (j > 0) j = fail[j-1];
else i++;
}
return -1;
}
//KMPFailure function
std::vector<int> computeFailFunction(const string& pattern)
{
std::vector <int> fail(pattern.size());
fail[0] = 0;
int m = pattern.size();
int j = 0;
int i = 1;
while (i < m)
{
if (pattern[j] == pattern[i])
{
fail[i] = j+1;
i++; j++;
}
else if (j > 0)
{
j = fail [j-1];
}
else
{
fail[i]= 0;
i++;
}
}
return fail;
}