int pi[1005]; void GetPrefixFunction(char *s, int sl) { pi[0] = 0, pi[1] = 0; for(int i = 1, k = 0; i < sl; ++i) { while(k && s[i] != s[k]) k = pi[k]; pi[i + 1] = (s[i] == s[k]) ? ++k : 0; } } //返回t在s中所有occurrence的首地址,s和t都是从0开始的 int ans[1005], atop; void KMP(char *s, int sl, char *t, int tl) { GetPrefixFunction(t, tl); atop = 0; for(int i = 0, k = 0; i < sl; ++i) { while(k && s[i] != t[k]) k = pi[k]; k += (s[i] == t[k]); if(k == tl) ans[++atop] = i - tl + 1; } }
来源:https://www.cnblogs.com/KisekiPurin2019/p/11904828.html