ZiliangZiliang

Site navigation

  • Mortgage comparison
  • Japan tax calculator
  • Programming
  • Algorithms
  • Machine learning
  • Misc
Engineering
Contact
中文

Site navigation

  • Mortgage comparison
  • Japan tax calculator
  • Programming
  • Algorithms
  • Machine learning
  • Misc
Engineering
Contact

Article directory

  • Programming Languages

    • Overview
    • Basics
    • Collections
    • Flow Control Statements
    • Function
    • Libraries and Modules
    • IO, File, and OS
    • Errors and Exceptions
    • Object-Oriented Design
    • Namespaces and Scopes
  • Data Structures and Algorithms

    • Overview
    • Math Formula
    • Math Code
    • Misc
    • String
    • Tree Traversal
    • Balanced Binary Trees
    • Heap
    • Segment Tree
    • Dynamic Programming
    • Tree Misc
    • Java
    • Disjoint Sets
    • Graph Traversal
    • Minimum Spanning Tree
    • Single-Source Shortest Paths
    • Strongly Connected Components
    • Cut Vertices and Bridges
    • Cache
    • Binary Search
    • Quicksort
    • Knapsack Problem
    • Vertex Cover Problem
    • Set Cover Problem
    • Principle Component Analysis
    • K-Center Problem

String

KMP

python
def kmp(string, pattern):
    m = len(string)
    n = len(pattern)
    nxt = [-1] * n  # i matches nxt[i]
    for i in range(1, n):
        j = nxt[i - 1]
        while j != -1 and pattern[j + 1] != pattern[i]:
            j = nxt[j]
        if pattern[j + 1] == pattern[i]:
            nxt[i] = j + 1

    i = j = 0
    while i < m and j < n:
        if string[i] == pattern[j]:
            i += 1
            j += 1
        else:
            j -= 1
            while j != -1 and string[i] != pattern[j + 1]:
                j = nxt[j]
            if string[i] == pattern[j + 1]:
                i += 1
                j += 2
            else:
                i += 1
                j += 1

    if j == n:
        return i - n
    else:
        return -1

java

Tests

python

java

Edit this page on GitHub
Last Updated: 9/10/26, 7:37 AM
Contributors: Lucien
Prev
Misc
Next
Tree Traversal