#include<iostream>
#include<string>
#include<vector>
using namespace std;
class KMP {
int* next;
public:
int KMP_Match_First(string s1, string s2 );//在文本串s1中找到第一个模式串s2的位置
void KMP_Match_All(string s1 , string s2 ); //在文本串s1中找到所有模式串s2的位置
void getNext(string s, int*& next);
};
int KMP::KMP_Match_First(string s1,string s2)
{
if (s1.length() < s2.length()) {
cout << "在文本串中未匹配到模式串" << endl;
return -1;
}
getNext(s2, next);
int j = 0;
for (int i = 0; i < s1.length(); i++)
{
while (j > 0 && s1[i] != s2[j])
j = next[j - 1];
if (s1[i] == s2[j])
j++;
if (j == s2.length())
{
cout << "在文本串中" << i - s2.length() + 1 << "位置匹配到模式串" << endl;
return i - s2.length() + 1;
}
}
cout << "在文本串中未匹配到模式串" << endl;
return -1;
}
void KMP::KMP_Match_All(string s1, string s2)
{
int pos = -1;
int i = 0;
vector<int> ans;
while (1)
{
pos = KMP_Match_First(s1, s2);
if (pos == -1 || s1.length() - s2.length() < s2.length())
break;
else {
ans.push_back(pos + i * s2.length());
s1.erase(s1.begin() + pos, s1.begin() + pos + s2.length() );
i++;
}
}
if(ans.empty()) cout << "在文本串中未匹配到模式串" << endl;
else {
cout << "在文本串中匹配到模式串!位置如下:" << endl;
for (vector<int>::iterator it = ans.begin(); it < ans.end(); it++)
cout << *it << '\t';
}
}
void KMP::getNext(string s, int*& next)
{
int len = s.length();
next = new int[len];
next[0] = 0;
int j = 0;
for (int i = 1; i < len; i++)
{
while (j > 0 && s[i] != s[j])
j = next[j - 1];
if (s[i] == s[j]) j++;
next[i] = j;
}
}
字符串比较之KMP算法完整实现
最新推荐文章于 2024-11-02 14:41:43 发布