我多次使用此代码,因为我有几个数据要发送到RabbitMQ
function ex_z_function(s) {
var n = s.length;
var z = Array(n).fill(0);
var i, l, r, maxi = 1;
for (i = 0, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[n - 1 - i - z[i]])
++z[i];
if ((i > 0) && (z[i] > z[maxi]))
maxi = i;
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
if (z[0] == n) {
return 0;
}
return n - z[maxi];
}
console.log(ex_z_function("a"));
console.log(ex_z_function("abc"));
console.log(ex_z_function("abac"));
console.log(ex_z_function("cabac"));
console.log(ex_z_function("21234"));
console.log(ex_z_function("abcdba"));
console.log(ex_z_function("abacaba"));
console.log(ex_z_function("vfvcabgvcvfv"));
答案 0 :(得分:1)