#include <the iostream> the using namespace STD; const int N = 10010 , M = 100010 ; int n-, m; char P [N], S [M]; int NE [N]; int main () { CIN >> n- >> P + . 1 >> m >> S + . 1 ; // find next: for short arrays for ( int I = 2 , J = 0 ; I <= n-; I ++ ) { the while (J && P [I] = P! [+ J . 1 ]) J = NE [J]; // the no match, an array of short matches start from the same position of the front edge of IF (P [I] == P [J + 1])j++; ne[i]=j; } //kmp匹配 for(int i=1,j=0;i<=m;i++) { while(j&&s[i]!=p[j+1])j=ne[j]; if(s[i]==p[j+1])j++; if(j==n)//匹配成功 { cout<<i-n<<' '; j=ne[j]; } } return 0; }
Be optimized by reducing the same string matching
Focus is on next array Seeking
j: an array is small, the matching process is performed, the comparison is the same whether the j + 1, j + 1 when the same is not to replace a position j has small front array matching, i.e., the corresponding value in the next.