KMP String Matching Algorithm

CK CK 3788 
Created at
Updated at  
673 0 0

KMP String Matching Algorithm is well-known algorithm for faster string search. KMP is, as you know, Knuth, Morris, and Pratt. It's complexity is O(n). n is the length of target string and O is big-O notation.

Here's the implemented algorithm.

 

////////////////////////////////////////////////////////////////////
// programmed by Kurapa Chunun Kang (kurapa@kurapa.com)
#ifndef __GLOBAL_H__
#define __GLOBAL_H__
 
#define MAX_STRING_SIZE                        100
#define MAX_PATTERN_SIZE                     100
 
int g_failure[MAX_PATTERN_SIZE];
int pattern_matching(char *str, char *pat);
void make_failure(char *pat);                                       

//////////////////////////////////////////////////////////////
#endif // __GLOBAL_H__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
// knuth,morris,pratt string matching algorithm
int pattern_matching(char *str, char *pat)
{
        int i = 0, j = 0;  // index
        int intStrLen = strlen(str);
        int intPatLen = strlen(pat);

        // debug
        // printf("intStrLen = %d intPatLen = %d ", intStrLen, intPatLen);
 
        // index should be longer than intStrLen & intPatLen
        while ((i < intStrLen) && (j < intPatLen))
        {
               if (str[i] == pat[j])
               {
                       i++;
                       j++;
               }
               else if (j == 0) i++;
               else j = g_failure[j-1] + 1;
        }
        return ((j == intPatLen) ? (i - intPatLen) : -1);
}
 
void make_failure(char *pat) // create failure function for target string
{
        int j = 0;
        int intPatLen = strlen(pat);
        g_failure[j] = -1; // the first value should be -1

        int i = 0;
        for ( j=1; j<intPatLen; j ++)
        {
               i = g_failure[j - 1];
               while ((pat[j] != pat[i+1]) && (i >= 0))
               {
                       i = g_failure[i];
               } /// end while

               if (pat[j] == pat[i+1]) g_failure[j] = i+1;
               else g_failure[j] = -1;
        } // end for


        // below is for debug
        printf( "g_failure[]={");
        for (j = 0; j < intPatLen; j ++)
        {
            if (j) printf( ",%d", g_failure[j]);
            else printf("%d", g_failure[j]);
        }
        printf( "} - where pattern=%s ", pat);

}

int main(int argc, char **argv)
{
        char string[] = "aababaaasdasdasdasdcas";
        char *pattern = "ababaa";
        int result = 0;
 
        make_failure(pattern);
 
        result = pattern_matching(string, pattern);
        // debug
        printf ("string is %s ", string);
        printf ("pattern is %s ", pattern);
        printf ("result = %d ", result);


        make_failure(pattern);

        pattern = "aabba";
        make_failure(pattern);

        pattern = "abababab";
        make_failure(pattern);

        pattern = "ababbaab";
        make_failure(pattern);

        return 0;
}

/* run result 
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

Z:내 문서Debug>kmp
g_failure[]={-1,-1,0,1,2,0} - where pattern=ababaa
intStrLen = 22 intPatLen = 6
string is aababaaasdasdasdasdcas
pattern is ababaa
result = 1
g_failure[]={-1,-1,0,1,2,0} - where pattern=ababaa
g_failure[]={-1,0,-1,-1,0} - where pattern=aabba
g_failure[]={-1,-1,0,1,2,3,4,5} - where pattern=abababab
g_failure[]={-1,-1,0,1,-1,0,0,1} - where pattern=ababbaab

Z:\내 문서\Debug>
*/
Tags Access Key Amazon Amazon CloudFront C++ Morris Pratt String Matching Algorithm String Search Algorithm Facebook X
Comments 0
Similar posts
  1. URL Encode, Decode function for MFC
    605
  2. How to load HTML resource on MFC ?
    841
  3. Makefile to automate the build process for C++
    279
  4. How to call SetTimer function on MFC CDialog class ?
    650
  5. How to search file on certain directory ?
    630
  6. How to run shell command by MFC ?
    436
  7. Binary Search Sample Code
    405
  8. Double Linked List based in C++
    796
  9. MFC based World Wide Web HTTP Server Source Code
    459
  10. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    472
  11. Fast and Good Keyboard/Mouse Test without the message handler
    982
  12. Simple CGI Programming in C
    545
  13. C++ CGI Example working on Apache
    484
  14. Architecting for Resilience: AWS High Availability Components Including API Gateway
    137
  15. Content Distribution for VOD streaming services in AWS
    10,355
  16. Live streaming / Static Content & Media Service based on AWS
    10,655
  17. Synchronous online gaming architecutre in AWS - Highly Available, Scalable & Elastic to support Millions of Players
    10,417
  18. Web Application Hosting provides the reliable, scalable, secure, and high-performance infrastructure
    10,615
  19. Media sharing service architecture in AWS
    10,366
  1. Conversation Multi-Agent Chatbot with On-the-Fly Code Execition via Microsoft AutoGen
    296
  2. Getting Started with FAISS: A CentOS 7 Installation Guide
    280
  3. CMake - a cross-platform build system generator that creates Makefiles used in C++ projects
    295
  4. How To Check If Your Printer Is Connected Using C#
    1,026
  5. How to get process id in C# like windows task manager ?
    870
  6. How to implement switch statement in C# ?
    987
  7. How to implement while loop in C# ?
    1,341
  8. How to delete file ?
    1,192
  9. How to convert integer to text string ?
    697
  10. How to convert text string to integer ?
    610
  11. How to set an certain color as transparent color on bitmap
    512
  12. How to resize and save PNG or Jpeg Image file ?
    631
  13. How to display message box in C#
    1,109
  14. How to convert bitmap image to jpeg image ?
    356
  15. To load image from file
    450
  16. URL Encode, Decode function for MFC
    605
  17. How to load HTML resource on MFC ?
    841
  18. How to get GM Time as String ?
    422
  19. Makefile to automate the build process for C++
    279
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    245
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260