Answers for "kmp algorithm"

C++
0

kmp algorithm

#include<bits/stdc++.h>
using namespace std;
void createlps(int lps[],string pattern,int n)
{
    int i=0;
    int j=1;
    lps[0]=0;
    while(j<n)
    {
        if(pattern[i]==pattern[j])
        {
            lps[j]=i+1;
            i++;
            j++;
        }
        else
        {
            if(i!=0)
            {
                i=lps[i-1];
            }
            else
            {
                lps[j]=0;
                j++;
            }
        }
    }
}
void kmp(string str,string pattern,int n,int lps[])
{
    int i=0;
    int j=0;
    int size_of_str=str.size();
    while(i<size_of_str)
    {
        if(pattern[j]==str[i])
        {
            i++;
            j++;
        }
        if(j==n)
        {
            cout<<"Found at:"<<i-j;
            j=lps[j-1];
        }
        else if(i<size_of_str&&pattern[j]!=str[i])
        {
            if(j!=0)
            {
                j=lps[j-1];
            }
            else
            {
                i++;
            }
        }
    }
}
int main()
{
    string str;
    cin>>str;
    string pattern;
    cin>>pattern;
    int n=pattern.size();
    int lps[n];
    createlps(lps,pattern,n);
    for(int i=0;i<n;i++)
    {
        cout<<lps[i]<<" ";
    }
    kmp(str,pattern,n,lps);
    return 0;
}
Posted by: Guest on August-09-2021
0

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;
        }
    }
}
Posted by: Guest on December-28-2020

Browse Popular Code Answers by Language