haikelfazzani
9/8/2017 - 5:40 PM

Z-function

Z-function

function zFunctionNaive(s) {
var result = [];
  for (var i = 0; i < s.length; i++) {
    result.push(0);
    for (var j = i; j < s.length; j++) {
      if (s[j] === s[result[i]]) result[i]++;
      else break;
    }
  }
  return result;
}

/*Example
For s = "acacbab", the output should be
zFunctionNaive(s) = [7, 0, 2, 0, 0, 1, 0].
*/