模板 - 字符串
KMP
namespace KMP{
int nxt[LEN];
void Init()
{
nxt[1]=0;
for(int i=2,j=0;i<=plen;i++)
{
while(j && p[j+1]!=p[i]) j=nxt[j];
if(p[j+1]==p[i]) j++;
nxt[i]=j;
}
return;
}
int Query()
{
int res=0;
for(int i=1;j=0;i<=slen;i++)
{
while(j && p[j+1]!=s[i]) j=nxt[j];
if(p[j+1]==s[i]) j++;
if(j==plen) res++,j=nxt[j];
}
return res;
}
}
字符串哈希
#define ULL unsigned long long
const ULL H=256;
ULL h[N];
ULL get_hash(char s[])
{
ULL res=0;
int len=strlen(s+1);
for(int i=1;i<=len;i++)
res=res*H+s[i];
return res;
}
TRIE 字典树
void insert(char *st)
{
int len=strlen(st),p=0;
for(int i=0;i<len;i++)
{
int ch=st[i]-'a'+1;
if(!trie[p][ch]) trie[p][ch]=++idx;
p=trie[p][ch];
}
end[p]++;
return;
}
int search(char *st)
{
int len=strlen(st),p=0;
for(int i=0;i<len;i++)
{
int ch=st[i]-'a'+1;
p=trie[p][ch];
if(!p) return 0;
}
return end[p];
}
本文采用 「CC-BY-NC 4.0」 创作共享协议,转载请注明作者及出处,禁止商业使用。
作者:Jerrycyx,原文链接:https://www.cnblogs.com/jerrycyx/p/18351566

浙公网安备 33010602011771号