来源:F04 扩展 KMP(Z 函数)_哔哩哔哩_bilibiliZ 函数(扩展 KMP) - OI Wiki (oi-wiki.org)
c++
复制代码
vector<int> z_function(string s) { int n = (int)s.length(); s = "#" + s; vector<int> z(n+1,0); z[1] = n; for (int i = 2, l = 0, r = 0; i <= n; ++i) { if(i <= r)z[i] = min(z[i - l + 1],r - i + 1); while(s[1 + z[i]] == s[i + z[i]])z[i] ++; if(i + z[i] - 1 > r)l = i,r = i + z[i] - 1; } return z; }