kmp algorithm
"""
This implementation demonstrates how 
to efficiently determine if a pattern 
string is a substring of some bigger,
target string.

Example: 
For following input values:
substring = "aefcd"
string = "dcaefcdcdaed"
Output would be: True

Let m be the size of the pattern and 
n be the size of the target string.

Time complexity: O(n+m)
Space complexity: O(m)
"""


def kmp_algorithm(string, substring):
    i, j = 0, 0
    """
    preprocess the pattern string by computing
    a failure function mapping indexes to shifts
    with the aim of reusing previously performed
    comparisons.
    """
    failure = compute_failure_function(substring)
    str_len, substr_len = len(string), len(substring)
    while i < str_len:
        if string[i] == substring[j]:
            # Pattern is found when its last char reached
            if j == substr_len - 1:
                return True
            i += 1
            j += 1
        elif j > 0:
            # Determine next continuation index in pattern
            # by consulting the failure function.
            j = failure[j-1]
        else:
            i += 1
    return False


def compute_failure_function(substring):
    # The failure function maps each index j
    # in pattern P to length of longest prefix
    # of P that is a suffix of P[1:j]
    j, i = 0, 1
    substr_len = len(substring)
    failure = [0] * substr_len
    while i < substr_len:
        if substring[j] == substring[i]:
            # We have matched j + 1 characters
            failure[i] = j + 1
            i += 1
            j += 1
        elif j > 0:
            # Place j just after a prefix that matches
            j = failure[j-1]
        else:
            i += 1
    return failure


print(kmp_algorithm("dcaefcdcdaed", "aefcd"))  # True
print(kmp_algorithm("dcaefccdaed", "aefcd"))  # False
kmp algorithm
#define ll long long int
#define vll vector<long long int>

ll kmp(string s)
{
    ll n = s.size();
    vll lps(n, 0); // longest prefix suffix
    for (ll i = 1; i < n; i++)
    {
        ll j = lps[i - 1];
        while (j > 0 && s[i] != s[j])
        {
            j = lps[j - 1];
        }
        if (s[i] == s[j])
        {
            j++;
        }
        lps[i] = j;
    }
    return lps[n - 1];
}
kmp c++
void computeLPSArray(char* pat, int M, int* lps)
{
    int len = 0;
    lps[0] = 0;
    int i = 1;
    while (i < M) {
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if (len != 0) {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}
int matchFound=0;
void KMPSearch(char* pat, char* txt)
{
    matchFound=0;
    int M = strlen(pat);
    int N = strlen(txt);
    int lps[M];
    computeLPSArray(pat, M, lps);
    int i = 0;
    int j = 0;
    while (i < N) {
        if (pat[j] == txt[i]) {
            j++;
            i++;
        }
        if (j == M) {
            matchFound++;
//            printf("Found pattern at index %d ", i - j);
            j = lps[j - 1];
        }
        else if (i < N && pat[j] != txt[i]) {
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
}
kmp algorithm
COMPUTE- PREFIX- FUNCTION (P)
 1. m ←length [P]		//'p' pattern to be matched
 2. Π [1] ← 0
 3. k ← 0
 4. for q ← 2 to m
 5. do while k > 0 and P [k + 1] ≠ P [q]
 6. do k ← Π [k]
 7. If P [k + 1] = P [q]
 8. then k← k + 1
 9. Π [q] ← k
 10. Return Π
kmp algorithm
KMP-MATCHER (T, P)
 1. n ← length [T]
 2. m ← length [P]
 3. Π← COMPUTE-PREFIX-FUNCTION (P)
 4. q ← 0		// numbers of characters matched
 5. for i ← 1 to n	// scan S from left to right 
 6. do while q > 0 and P [q + 1] ≠ T [i]
 7. do q ← Π [q]		// next character does not match
 8. If P [q + 1] = T [i]
 9. then q ← q + 1		// next character matches
 10. If q = m			           // is all of p matched?
 11. then print "Pattern occurs with shift" i - m
 12. q ← Π [q]				// look for the next match

Python相关代码片段

drop one table sqlalchemy

python code to remove last character from string

fastapi get body on http middleware

custom neural network in keras

python selenium execute_script

db model for blog

yolov5 opencv

Get first 100 lines of file - python

python playground

print number pattern using for loop in python

ollama python

no module named 'wget'

No module named 'langchain'

failed to build wxpython

python vs c#

rabbitmq python example

change the django url prefix name

np.linspace is not defined python

LLM beguiner guide python

python parquet file to csv

python best practices

yolov5 without net

save variable as pkl python

python [-9:]

eigenface python

'DataFrame' object has no attribute 'dtype'

unable to enable maximize window tkinter

rabbit and fox numpy python

lstm in keras

neural network in keras

resnet50 in keras

autoencoder in keras

cnn in keras

tensor in keras

pyTelegramBotAPI edit photo

print api python

how to get values but not index from pandas series

how to get mode of a column from pandas

bayesian neural network pymcmc

lda python

back propagation python

logical syntax is not none python

register model django

Descending Selection sort

Selection sort with while loops

Selection sort with for loops

Doubling Algorithm for cluster analysis in python

Tkinter widgets

nameerror: name 'callable' is not defined

NameError: name 'Union' is not defined

Make a widget customtkinter python

nn module pytorch

import tf python

Spark SEssion object

Implement Bubble sort with while loops

Unoptimized bubble sort algorithm

Optimized bubble sort algorithm

how to get today's date in python

st_aggrid install

python venv pip blocked by admin windows

numpy matrix from lists of different leght

python postgres auto commit

dotenv install python

np mean axis

LinkExtractor Object

admin django documentation

Python native Convolution implementation

is django monolithic

what is function call with an llm

np array to series

dht22 micropython pico

disable slash command discord.py

python docker compose not printing

tabnet probabilities

python venv: no such file or directory

find most common words in string python

histogram equalization using pillow

Django squash migrations

swap first and last letter in string in array

sor a lit in python