本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

文字列アルゴリズム ドキュメント
文字列アルゴリズム
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
ディスカッション

文字列アルゴリズム ガイド · 2/6

How It Works

この章は現在、英語でのみ提供しています。

This chapter traces KMP, Rabin-Karp, tries and the Z-algorithm by hand on small inputs. Working out the tables yourself makes the code in the next chapter much easier to read.

KMP step 1: the prefix function (failure table)

The prefix function pi[i] is the length of the longest border of the first i + 1 characters of the pattern (p[0..i]). It is also called the failure function or failure table. Here it is for ababaca.

i0123456
p[i]ababaca
pi[i]0012301

The computation runs left to right and carries k, the border length at the previous position.

  1. i = 1: p[1] = b differs from p[0] = a and k = 0, so pi[1] = 0.
  2. i = 2: p[2] = a equals p[0], so k = 1 and pi[2] = 1.
  3. i = 3, 4: the characters keep matching and k grows to 2, then 3.
  4. i = 5: p[5] = c differs from p[3] = b. Instead of starting over, fall back to a shorter border: k = pi[k - 1] = pi[2] = 1. p[1] = b still differs, so k = pi[0] = 0; p[0] = a differs too, and pi[5] = 0.
  5. i = 6: p[6] = a equals p[0], so pi[6] = 1.

Step 4 is the key idea. On a mismatch you jump straight to the next shorter border inside the current one. Because a border of a border is itself a border, no candidate is skipped.

def prefix_function(p: str) -> list[int]:
    pi = [0] * len(p)
    k = 0
    for i in range(1, len(p)):
        while k > 0 and p[i] != p[k]:
            k = pi[k - 1]
        if p[i] == p[k]:
            k += 1
        pi[i] = k
    return pi


print(prefix_function("ababaca"))  # [0, 0, 1, 2, 3, 0, 1]

KMP step 2: scanning the text

Searching works the same way. k is the number of pattern characters matched so far, and the text pointer i never moves backwards. Search for () in :

この章について質問がありますか?
前の章Concepts次の章Implementation
abab
pi = [0, 0, 1, 2]
abababcabab
iCharActionk afterResult
0-3a b a ball match4match at 0, k = pi[3] = 2
4amatches p[2] = a3
5bmatches p[3] = b4match at 2, k = 2
6cfails against p[2], then p[0]0
7-10a b a ball match4match at 7

Setting k = pi[m - 1] after a match, instead of 0, is what finds overlapping occurrences such as the ones at 0 and 2.

Rabin-Karp: the rolling hash

Rabin-Karp compares the hash of each length-m window with the hash of the pattern. When the window slides by one, the hash is not recomputed from scratch: the leading character is removed and the new one added in O(1).

h(s) = (s[0]·B^(m-1) + s[1]·B^(m-2) + ... + s[m-1]) mod M
next window: h' = ((h - s[i]·B^(m-1))·B + s[i+m]) mod M

To keep the numbers readable, use a digit string with B = 10 and M = 11. The text is 31415926, the pattern is 1592, and the pattern hash is 1592 mod 11 = 8.

StartWindowHashVerdict
031416skip
114157skip
241591skip
315928characters compared: match
459268characters compared: no match (false positive)

As the last row shows, equal hashes do not guarantee equal strings, so a hash hit must always be confirmed by comparing characters. Real code uses a large prime modulus such as 10**9 + 7 and a random base to make collisions rare.

def window_hashes(text: str, m: int, base: int = 10, mod: int = 11) -> list[int]:
    high = pow(base, m - 1, mod)
    h = 0
    for ch in text[:m]:
        h = (h * base + int(ch)) % mod
    out = [h]
    for i in range(len(text) - m):
        h = ((h - int(text[i]) * high) * base + int(text[i + m])) % mod
        out.append(h)
    return out


print(window_hashes("31415926", 4))  # [6, 7, 1, 8, 8]

Tries: a tree of shared prefixes

A trie is a tree you walk down one character at a time. After inserting car, cart, cat and dog, the common prefix ca is stored once. A * marks a node where a word ends.

(root)
 ├─ c ─ a ─ r* ─ t*
 │        └─ t*
 └─ d ─ o ─ g*

To autocomplete ca, walk down c then a and collect every end-of-word mark below that node: car, cart, cat. The walk costs time proportional to the prefix length, independent of how many words the dictionary holds.

The Z-algorithm in brief

In the Z-array, z[i] is the length of the longest common prefix of s[i:] and s. For aabxaab it is [7, 1, 0, 0, 3, 1, 0] (by convention z[0] is the length or 0). To search, build the Z-array of pattern + "$" + text and report positions where the value equals m; the separator $ must not appear in either string. By reusing the rightmost interval [l, r) already matched (the Z-box), the whole array is computed in O(n + m).

Summary

  • On a mismatch the prefix function falls back to a border of a border, so the text pointer never moves back.
  • After a match KMP sets k = pi[m - 1], which also finds overlapping occurrences.
  • Rabin-Karp updates each window hash in O(1) and confirms hash hits character by character to reject false positives.
  • Tries share common prefixes; the Z-array solves the same problems as KMP from a different angle.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。