private static byte[] calculateNext2(byte[] pattern) {
        int m = pattern.length;
        byte[] next = new byte[m];
        byte i = 1;
        byte j = 0;
        next[0] = -1;
        boolean ok = true;
        while (i < m) {
            /*
             * If these two match, we cannot possibly have a candidate as we
             * already know pattern[i] is a failed match, so shift the match
             * pointer.
             */
            while (j >= 0 && pattern[i] == pattern[j])
                --j;
            /*
             * If all items from 0 to j - 1 match, 'j' is a good candidate for
             * the next table.
             */
            byte k = (byte) (j - 1);
            while (k >= 0 && ok)
                if (pattern[k] != pattern[k + (i - j)])
                    ok = false;
                else
                    --k;
            /*
             * Possible candidate for next table?
             */
            if (!ok) {
                --j;
                ok = true;
            } else {
                /*
                 * Shift match and pattern pointers up next to each other
                 */
                next[i] = j;
                j = i++;
            }
        }
        return next;
    }