【模板】KMP字符串匹配【KMP】
给出两个字符串s1和s2,其中s2为s1的子串,求出s2在s1中所有出现的位置。 思路: K M P 算法模板题。 K M P 这个算法一开始真的很难懂,但是接触后过一会再研究就会豁然开朗。这个东西也很难解释原理,只有自己搞懂。 推荐的 K M P 讲解: https://blog.csdn.net/starstar1992/article/details/54913261/ 时间复杂度 O ( n ) ,暴力时间复杂度 O ( n × m ) #include <cstdio> #include <iostream> #include <cstring> using namespace std; int next[ 1000101 ],n,m,j; char a[ 1000101 ],b[ 1000101 ]; int main() { cin >>a+ 1 ; cin >>b+ 1 ; n =strlen(a+ 1 ); m =strlen(b+ 1 ); next[ 1 ]= 0 ; for ( int i= 1 ;i<m;i++) // 求next数组 { while (b[i+ 1 ]!=b[j+ 1 ]&&j> 0 ) j=next[j]; // 不匹配 if (b[i+ 1 ]==b[j+ 1 ]) j++; // 匹配成功 next[i+ 1 ]= j; } j =