KMP算法,网上有很多文章讲解,也有很多视频,内容怎么样,能不能讲明白这里就不置评了。
我当然也不会讲,讲不出来,也是一知半解。所以这里只贴一下代码,方便日后查看。
题目链接:http://hihocoder.com/problemset/problem/1015
#include <iostream> #include <string> #include <cstring> using namespace std; string str, ptr; int nex[10100]; void make_nex() { memset( nex, 0, sizeof(nex) ); nex[0] = -1; int i = 0, j = -1; int plen = ptr.size(); // 这里需要多算一位(平时kmp算到plen-1即可) // 因为涉及到模式串回溯,当一次匹配完成时 不一定是从头进行下次匹配 // 举个例子就是 ptr:BABA str:BABABA // 可以试试这里 改为 plen-1 运行上一行的样例进行查看理解 while ( i < plen ) { if ( j == -1 || ptr[i] == ptr[j] ) { i ++; j ++; if ( ptr[i] != ptr[j] ) nex[i] = j; else nex[i] = nex[j]; } else { j = nex[j]; } } // for ( int i = 0 ; i <= plen ; ++ i ) { // cout << nex[i] << " "; // } cout << endl; } int kmp() { make_nex(); int ans = 0; int i = 0, j = 0, slen = str.size(), plen = ptr.size(); while ( i < slen ) { if ( j == -1 || str[i] == ptr[j] ) { i ++; j ++; } else { j = nex[j]; } if ( j == plen ) { ans ++; j = nex[j]; } } return ans; } int main() { std::ios::sync_with_stdio(false); int T; cin >> T; while ( T -- ) { cin >> ptr >> str; cout << kmp() << endl; } return 0; }