#include <iostream>
#include <string>
using namespace std;
int Brute_force_string_matching(string &s, string &p) // 字符串暴力匹配
{
size_t i = 0;
size_t j = 0;
size_t slen = s.size();
size_t plen = p.size();
if (slen < plen)
{
return -1;
}
while (i < slen && j < plen)
{
if (s[i] == p[j])
{
++i;
++j;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == plen)
{
return i - j; // 返回匹配的位置
}
else
{
return -1;
}
}
int get_next(string &p, int next[]) //求next数组无优化版
{
int plen = p.size();
next[0] = -1;
int k = -1;
int j = 0;
while (j < plen - 1)
{
if (k == -1 || p[k] == p[j]) // p[k]前缀 p[j]后缀
{
++j;
++k;
next[j] = k;
}
else
{
k = next[k];
}
}
return 0;
}
int get_nextval(string &p, int next[]) // 求next数组的优化版
{
int plen = p.size();
next[0] = -1;
int k = -1;
int j = 0;
while (j < plen - 1)
{
if (k == -1 || p[k] == p[j])
{
++j;
++k;
if (p[j] != p[k]) // p[j] == p[next[j]]
{
next[j] = k;
}
else
{
next[j] = next[k];
}
}
else
{
k = next[k];
}
}
return 0;
}
int kmp_search(string &s, string &p, int next[]) // kmp匹配
{
int i = 0; int j = 0;
int slen = s.size(); int plen = p.size();
if (slen < plen)
{
return -1;
}
while (i < slen && j < plen)
{
if (j == -1 || s[i] == p[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == plen)
{
return i - j;
}
else
{
return -1;
}
}
int main()
{
string s = "abacababc";
string p = "abab";
int next[10] = {0};
get_next(p, next);
cout << kmp_search(s, p, next) << endl;
get_nextval(p, next);
cout << kmp_search(s, p, next) << endl;
return 0;
}
kmp
最新推荐文章于 2022-07-28 23:58:32 发布