本文へスキップ

リソース · ガイド・記事

Rabin Karp Algorithm

ページ上で Karp と Rabin の考案とされている、ハッシュを使う文字列探索 Rabin-Karp を紹介し、ハッシュが一致しても直接の比較が必要な理由を説明しています。

確認日

元のサイトを開く: Rabin Karp Algorithm (元のサイトを新しいタブで開きます)

このトピックを練習技術 / コーディング モードで練習用面接官を開きます。問題はそこで選びます。

ロードマップに追加

取り組んでいるロードマップにこのリソースを追加できます。自分用の追加リソースとして表示され、ロードマップの手順は変わらず、記録した手順数にも数えられません。

出典コンテンツの言語:英語

In computer science, the Rabin–Karp algorithm or Karp–Rabin algorithm is a string searching algorithm created by Richard M. Karp and Michael O. Rabin (1987) that uses hashing to find any one of a set of pattern strings in a text. The Rabin–Karp algorithm seeks to speed up the testing of equality of the pattern to the substrings in the text by using a hash function. A hash function is a function which converts every string into a numeric value, called its hash value; for example, we might have hash('hello') = 5. The algorithm exploits the fact that if two strings are equal, their hash values are also equal. Thus, string matching is reduced (almost) to computing the hash value of the search pattern and then looking for substrings of the input string with that hash value. However, there are two problems with this approach. First, because there are so many different strings and so few hash values, some differing strings will have the same hash value. If the hash values match, the pattern and the substring may not match; consequently, the potential match of search pattern and the substring must be confirmed by comparing them; that comparison can take a long time for long substrings…

PrepKit の概要

この概要は PrepKit 編集部がソースリポジトリをもとに執筆・確認したもので、リソース本文の引用ではありません。

対象
ソースにレベルの記載はありません
形式
リファレンス

扱っている内容

  • パターン照合をハッシュ値の比較に置き換える考え方と、衝突があるために確認の段階が必要になることを説明しています
  • ローリングハッシュで連続する部分文字列のハッシュを安く計算できると述べ、例では Rabin fingerprint ではなく多項式ハッシュを使っているとしています
  • 平均と最良で時間 O(n + m)、空間 O(p)、最悪で O(n * m) を示しています
  • 複数パターンの用途として盗用の検出を挙げています

使い方

PrepKit の学習アドバイスであり、ソースの主張ではありません。

多項式ローリングハッシュを実装してテキスト上をスライドさせ、ハッシュが一致するたびに、直接の比較で確認されたかどうかを記録してください。そうすれば最悪ケースがどこから生じるかを説明できるはずです。

範囲と制約

概念の説明のみで、ローリングハッシュの計算例、コードの解説、演習はありません。詳細は Wikipedia と YouTube のリンクに任されています。

利用方法と形式

GitHub の trekhleb/javascript-algorithms(MIT)にある README です。英語で、無料で読めます。

PrepKit が 2026/10/02 に確認しました。 リソースの出典のコミット: 85293e3e2b88

この概要の根拠
  • src/algorithms/string/rabin-karp/README.md

この項目を掲載しているページ

PrepKit ニュースレターを受け取る

任意です。PrepKit の利用には必要ありません。

メールアドレスの取り扱いについて