串的模式匹配
(1)KMP算法
#include <iostream>
#include <string>
using namespace std;
void getnext(int *next,const string&s)
{
next[0] = 0;
int j = 0;
for (int i = 1; i < s.size(); i++) {
while (j > 0 && s[i] != s[j]) {
j = next[j - 1];
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
int KMP(string S,string T)
{
if (T.size() == 0) {
return 0;
}
int* next = new int[T.size()];
getnext(next, T);
int j = 0;
for (int i = 0; i < S.size(); i++) {
while (j > 0 && S[i] != T[j]) {
j = next[j - 1];
}
if (S[i] == T[j]) {
j++;
}
if (j == T.size()) {
return i - T.size() + 1;
}
}
return -1;
}
int main()
{
string s = "aaaaab";
string t = "aaab";
cout << KMP(s, t);
}
(2)BF算法
#include <iostream>
#include <string>
using namespace std;
int index(string S,string T)
{
int i = 0, j = 0;
while (i < S.size() && j < T.size())
{
if (S[i] == T[j]) {
i++;
j++;
}
else {
i = i - j + 1;
j = 0;
}
}
if (j >= T.size()) {
return i - T.size();
}
else {
return -1;
}
}
int main()
{
string s = "aaaaab";
string t = "aaab";
cout << index(s, t);
}