Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Kyo-s-s/Library

:heavy_check_mark: Zalgorithm
(String/Zalgorithm.hpp)

Zalgorithm

(1) vector<int> Zalgorithm(string S)
(2) vector<int> Zalgorithm(vector<T> S)

$S$ の長さを $N$ として, 長さ $N$ の配列を返す. $i$番目の要素はs[0..N)s[i..N)の最長共通接頭辞.

計算量

Verified with

Code

vector<int> Zalgorithm(const string &S) {
    vector<int> Z(S.size());
    Z[0] = (int)S.size();
    int i = 1, j = 0;
    while(i < S.size()) {
        while(i + j < (int)(S.size()) && S[j] == S[i + j]) j++;
        Z[i] = j;

        if(j == 0) {
            i++;
            continue;
        }

        int k = 1;
        while(k < j && k + Z[k] < j) {
            Z[i + k] = Z[k];
            k++;
        }
        i += k;
        j -= k;
    }
    return Z;
}

template<class T>
vector<int> Zalgorithm(const vector<T> &S) {
    vector<int> Z(S.size());
    Z[0] = (int)S.size();
    int i = 1, j = 0;
    while(i < S.size()) {
        while(i + j < (int)(S.size()) && S[j] == S[i + j]) j++;
        Z[i] = j;

        if(j == 0) {
            i++;
            continue;
        }

        int k = 1;
        while(k < j && k + Z[k] < j) {
            Z[i + k] = Z[k];
            k++;
        }
        i += k;
        j -= k;
    }
    return Z;
}
#line 1 "String/Zalgorithm.hpp"
vector<int> Zalgorithm(const string &S) {
    vector<int> Z(S.size());
    Z[0] = (int)S.size();
    int i = 1, j = 0;
    while(i < S.size()) {
        while(i + j < (int)(S.size()) && S[j] == S[i + j]) j++;
        Z[i] = j;

        if(j == 0) {
            i++;
            continue;
        }

        int k = 1;
        while(k < j && k + Z[k] < j) {
            Z[i + k] = Z[k];
            k++;
        }
        i += k;
        j -= k;
    }
    return Z;
}

template<class T>
vector<int> Zalgorithm(const vector<T> &S) {
    vector<int> Z(S.size());
    Z[0] = (int)S.size();
    int i = 1, j = 0;
    while(i < S.size()) {
        while(i + j < (int)(S.size()) && S[j] == S[i + j]) j++;
        Z[i] = j;

        if(j == 0) {
            i++;
            continue;
        }

        int k = 1;
        while(k < j && k + Z[k] < j) {
            Z[i + k] = Z[k];
            k++;
        }
        i += k;
        j -= k;
    }
    return Z;
}
Back to top page