先贴几个板子,记录一下
kmp为单模匹配算法,这个博客讲的很好:https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html,透彻明了,其中next数组即为当前字符前已匹配的字符中最长的相同前后缀长度
贴上板子:
//kmp和优化后的kmp
#include <iostream>
#include <cstring>
using namespace std;
void getNext(char* p, int next[])
{
int plen = strlen(p);
next[0] = -1;
int j = -1;
int i = 0;
while (i < plen - 1)
{
if (j == -1 || p[i] == p[j])
{
++j;
++i;
next[i] = j;
//
if (p[i] != p[j])
next[i] = j;
else
next[i] = next[j];
}
else
j = next[j];
}
}
int kmpSearch(char* s, char* p, int next[])
{
int i = 0;
int j = 0;
int slen = strlen(s);
int plen = strlen(p);
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()
{
char str1[100] = "cdbab";
char str2[100] = "ab";
int next[100] = { 0 };
getNext(str1, next);
cout << kmpSearch(str1, str2, next) << endl;
for (int i = 0; i < 20; ++i)
{
cout << next[i] << " ";
}
std::cout << "Hello World!\n";
}
对于字典树呢,有指针和数组两种实现,其中指针比较省空间,也易错。字典树是个多功能的东西,可以高效查询单词,可以对字符串进行排序,也可以求最长公共前缀,amazing!上板子:
指针和数组:https://blog.csdn.net/king_cannon_fodder/article/details/77175620
数组:https://blog.csdn.net/u013588639/article/details/38406453
关于AC自动机这个多模匹配算法,时间有点紧还没看呢哈哈。。。