リソース · ガイド・記事
Z Algorithm
Z 配列による線形時間のパターン探索を扱います。Z 配列の各要素は、その位置から始まる部分文字列が文字列の先頭部分とどこまで一致するかを記録します。
確認日
元のサイトを開く: Z Algorithm (元のサイトを新しいタブで開きます)このトピックを練習技術 / コーディング モードで練習用面接官を開きます。問題はそこで選びます。
ロードマップに追加
取り組んでいるロードマップにこのリソースを追加できます。自分用の追加リソースとして表示され、ロードマップの手順は変わらず、記録した手順数にも数えられません。
出典コンテンツの言語:英語
The Z-algorithm finds occurrences of a "word" W within a main "text string" T in linear time O(|W| + |T|). Given a string S of length n, the algorithm produces an array, Z where Z[i] represents the longest substring starting from S[i] which is also a prefix of S. Finding Z for the string obtained by concatenating the word, W with a nonce character, say $ followed by the text, T, helps with pattern matching, for if there is some index i such that Z[i] equals the pattern length, then the pattern must be present at that point. While the Z array can be computed with two nested loops in O(|W| * |T|) time, the following strategy shows how to obtain it in linear time, based on the idea that as we iterate over the letters in the string (index i from 1 to n - 1), we maintain an interval [L, R] which is the interval with maximum R such that 1 ≤ L ≤ i ≤ R and S[L...R] is a prefix that is also a substring (if no such interval exists, just let L = R = - 1). For i = 1, we can simply compute L and R by comparing S[0...] to S[1...].
PrepKit の概要
この概要は PrepKit 編集部がソースリポジトリをもとに執筆・確認したもので、リソース本文の引用ではありません。
- 対象
- ソースにレベルの記載はありません
- 形式
- リファレンス
扱っている内容
- パターン、$ などの区切り文字、テキストを連結し、パターン長に等しい Z 値を探すという探索の工夫を示しています
- 計算を線形に保つ [L, R] の区間を紹介しています
- aaaaaa や abababab を含む4つの Z 配列の例を挙げています
- 時間 O(|W| + |T|)、空間 O(|W|) と述べています
使い方
PrepKit の学習アドバイスであり、ソースの主張ではありません。
挙げられた例の Z 配列を手で求めてページと照らし合わせ、そのうえで [L, R] 版を実装し、パターンの一致をすべて見つけられることを確認してください。
範囲と制約
区間の更新ルールは概略だけで、Z-box の図は外部にある画像です。完全な導出はリンク先の GeeksForGeeks、YouTube、ブログにあります。
利用方法と形式
GitHub の trekhleb/javascript-algorithms(MIT)にある README です。英語で、無料で読めます。
PrepKit が 2026/10/02 に確認しました。 リソースの出典のコミット: 85293e3e2b88
この概要の根拠
- src/algorithms/string/z-algorithm/README.md
この項目を掲載しているページ
PrepKit ニュースレターを受け取る
任意です。PrepKit の利用には必要ありません。