版本比较
KMP 学习笔记
正文
增加 6 行删除 6 行
2 行未改动34567789101120 行未改动3233343536363738394012 行未改动5354555657575859606131 行未改动939495969797989910010114 行未改动11611711811912012012112212312432 行未改动15715815916016116116216316416563 行未改动2 行未改动这是学长讲的内容,我又重新整理了一遍。保证简单易懂。
# 字符串的若干记号
- $s,t$ 等一般表示一个字符串,一般用 $n$ 表示其长度。 - $s,t$ 等一般表示一个字符串,一般用 $n$ 表示其长度。- $s[a,b]$:字符串 $s$ 中第 $a$ 位到第 $b$ 位组成的字串。- $pre(i)=s[1,i]$。- $suf(i)=s[n-i+1,n]$。- $bd(s)= \{i|pre(i)=suf(i)\}$。注意有时在题目中会要求 $i\le n$,而有时则是 $i<n$,需要注意。20 行未改动const int N=1e5+5;struct Hash{ const ll M=1e9+97; const ll B=131; string s; string s; int len; ll pw[N],hsh[N]; void pre(){ len=s.size(),pw[0]=1,hsh[0]=s[0];12 行未改动 int n=h1.len; for(int i=1;i<=n;i++){ printf("border of pre(%d):",i); for(int j=1;j<i;j++) if(h1.qry(1,j)==h1.qry(i-j+1,i)) if(h1.qry(1,j)==h1.qry(i-j+1,i)) printf(" %d",j),fail[i]=j; puts(""); } for(int i=1;i<=n;i++) printf("%d ",fail[i]);31 行未改动const int N=1e5+5;struct Hash{ const ll M=1e9+97; const ll B=131; string s; string s; int len; ll pw[N],hsh[N]; void pre(){ len=s.size(),pw[0]=1,hsh[0]=s[0];14 行未改动 if(i!=1&&h1.s[0]==h1.s[i-1]) bd[i].push_back(1); //注意特判长度为 1 的 boader。 //此外还需要判断 i=1 时不符合 boader 定义中 i<n 的情况。你可以把 i!=1&& 去掉试试。 for(int j:bd[i-1]) if(h1.qry(1,j+1)==h1.qry(i-(j+1)+1,i)) if(h1.qry(1,j+1)==h1.qry(i-(j+1)+1,i)) bd[i].push_back(j+1); printf("border of pre(%d):",i); for(int j:bd[i]) printf(" %d",j); puts("");32 行未改动 if(s[j+1]==s[i]){ fail[i]=j+1; break; } if(fail[i]==0&&s[1]==s[i]&&i>1) fail[i]=1; if(fail[i]==0&&s[1]==s[i]&&i>1) fail[i]=1; } for(int i=1;i<=n;i++) printf("%d ",fail[i]); return 0;}63 行未改动