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

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらく

開発ツール

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

サーバー

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

はじめる

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

ニュース

今日の開発ニュース言語・フレームワーク・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ツールの問題ショーケース
ポリシープライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
012345678901234567890123456789012345678901234567890123456789
昨日
012345678901234567890123456789012345678901234567890123456789
累計閲覧
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
商号
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
ディスカッション

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

Complexity

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

This chapter analyzes time and space in terms of text length n, pattern length m and alphabet size σ. String algorithms often behave very differently on average and in the worst case, so both are covered.

Naive matching

There are n - m + 1 starting positions and up to m comparisons at each, so the worst case is O(n·m). Text aaaa...a with pattern aa...ab is the textbook bad input. On the other hand, with a large alphabet and text that looks random, most attempts fail on the first or second character, so the average is close to O(n). Extra memory is O(1).

Why KMP is linear

KMP's inner while loop looks like a nested loop, yet the total cost is O(n + m). An amortized argument shows why.

  1. k grows by at most 1 per text character, so its total increase is at most n.
  2. Every iteration of the while loop decreases k by at least 1, and k never drops below 0.
  3. Therefore the while loop cannot run more times in total than k ever increased, which is at most n.

The same argument gives O(m) for the prefix function. Space is O(m) for the pi array, and because the text is read strictly left to right, KMP works unchanged on streams.

Counting comparisons makes the difference concrete.

def naive_comparisons(text: str, pattern: str) -> int:
    count = 0
    for s in range(len(text) - len(pattern) + 1):
        for j in range(len(pattern)):
            count += 1
            if text[s + j] != pattern[j]:
                break
    return count


def kmp_comparisons(text: str, pattern: str) -> int:
    pi = [0] * len(pattern)
    k = 0
    for i in range(1, len(pattern)):
        while k > 0 and pattern[i] != pattern[k]:
            k = pi[k - 1]
        if pattern[i] == pattern[k]:
            k += 1
        pi[i] = k
    count, k = 0, 0
    for ch in text:
        while True:
            count += 1
            if ch == pattern[k]:
                k += 1
                break
            if k == 0:
                break
            k = pi[k - 1]
        if k == len(pattern):
            k = pi[k - 1]
    return count


text, pattern = "a" * 10_000, "a" * 99 + "b"
print(naive_comparisons(text, pattern))  # 990100
print(kmp_comparisons(text, pattern))    # 19901

On the same input the naive method makes about 990,000 comparisons and KMP about 20,000. KMP never exceeds 2n comparisons during the scan.

Rabin-Karp

Rolling the hash costs O(1) per window, so hashing is overall. Each hash hit costs an check, so with real occurrences and rare collisions the expected time is . If the modulus is small, or the input was crafted to collide, almost every window needs a check and the worst case becomes . Space is .

この章について質問がありますか?
前の章Implementation次の章Practice Problems
O(n + m)
O(m)
occ
O(n + m + occ·m)
O(n·m)
O(1)

Rabin-Karp shines when you look for many patterns of the same length. Put the pattern hashes in a set and each window needs one set lookup, so k patterns cost O(n + k·m) expected time.

def multi_rabin_karp(text: str, patterns: set[str], base: int = 911382323, mod: int = (1 << 61) - 1) -> list[tuple[int, str]]:
    m = len(next(iter(patterns)))
    assert all(len(p) == m for p in patterns)
    def h(s: str) -> int:
        v = 0
        for ch in s:
            v = (v * base + ord(ch)) % mod
        return v
    wanted = {h(p) for p in patterns}
    high = pow(base, m - 1, mod)
    out, cur = [], h(text[:m])
    for i in range(len(text) - m + 1):
        if cur in wanted and text[i:i + m] in patterns:
            out.append((i, text[i:i + m]))
        if i + m < len(text):
            cur = ((cur - ord(text[i]) * high) * base + ord(text[i + m])) % mod
    return out


print(multi_rabin_karp("the cat sat on the mat", {"cat", "mat", "dog"}))
# [(4, 'cat'), (19, 'mat')]

Tries

Insert, lookup and walking to a prefix all cost O(L) for a key of length L, no matter how many words are stored. Autocomplete adds the number of nodes visited while collecting results. With N total characters there are at most N nodes, so space is O(N·σ) with fixed-size child arrays or O(N) with hash maps. When words share few prefixes the node count explodes, which is why compressed tries (radix trees) merge chains of single-child nodes.

A sorted list plus binary search also answers prefix queries, and uses far less memory when the word list rarely changes.

import bisect

words = sorted(["car", "cart", "cat", "dog", "dot"])
lo = bisect.bisect_left(words, "ca")
hi = bisect.bisect_left(words, "cb")   # the next prefix after "ca"
print(words[lo:hi])  # ['car', 'cart', 'cat']

Comparison

AlgorithmPreprocessingSearch (worst)Search (typical)Extra spaceNotes
NaivenoneO(n·m)near O(n)O(1)simplest to write
KMPO(m)O(n)O(n)O(m)never rereads the text
Z-algorithmO(n + m)O(n + m)O(n + m)O(n + m)short code, many uses
Rabin-KarpO(m)O(n·m)O(n + m)O(1)many patterns, substring hashing
Boyer-Moore familyO(m + σ)O(n·m)can be sublinearO(m + σ)fast for long patterns, large alphabets
Aho-CorasickO(total pattern length)O(n + matches)sameproportional to patternsmany patterns in one pass
TrieO(N)O(L) per querysameO(N) to O(N·σ)dictionary prefix lookup

Summary

  • KMP and Z are linear even in the worst case; the amortized argument bounds total decreases by total increases.
  • Rabin-Karp is linear in expectation but can degrade to O(n·m) under heavy collisions.
  • Trie operations depend only on key length, but memory is costly, so consider radix trees or a sorted list too.

コメント 0件

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

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