Open In App

C# Program for KMP Algorithm for Pattern Searching

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.  Examples:

Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12
 
 

Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results. 

C#




// C# program for implementation of KMP pattern
// searching algorithm
using System;
 
class GFG {
 
    void KMPSearch(string pat, string txt)
    {
        int M = pat.Length;
        int N = txt.Length;
 
        // create lps[] that will hold the longest
        // prefix suffix values for pattern
        int[] lps = new int[M];
        int j = 0; // index for pat[]
 
        // Preprocess the pattern (calculate lps[]
        // array)
        computeLPSArray(pat, M, lps);
 
        int i = 0; // index for txt[]
        while (i < N) {
            if (pat[j] == txt[i]) {
                j++;
                i++;
            }
            if (j == M) {
                Console.Write("Found pattern "
                              + "at index " + (i - j));
                j = lps[j - 1];
            }
 
            // mismatch after j matches
            else if (i < N && pat[j] != txt[i]) {
                // Do not match lps[0..lps[j-1]] characters,
                // they will match anyway
                if (j != 0)
                    j = lps[j - 1];
                else
                    i = i + 1;
            }
        }
    }
 
    void computeLPSArray(string pat, int M, int[] lps)
    {
        // length of the previous longest prefix suffix
        int len = 0;
        int i = 1;
        lps[0] = 0; // lps[0] is always 0
 
        // the loop calculates lps[i] for i = 1 to M-1
        while (i < M) {
            if (pat[i] == pat[len]) {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {
                // This is tricky. Consider the example.
                // AAACAAAA and i = 7. The idea is similar
                // to search step.
                if (len != 0) {
                    len = lps[len - 1];
 
                    // Also, note that we do not increment
                    // i here
                }
                else // if (len == 0)
                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }
 
    // Driver program to test above function
    public static void Main()
    {
        string txt = "ABABDABACDABABCABAB";
        string pat = "ABABCABAB";
        new GFG().KMPSearch(pat, txt);
    }
}
 
// This code has been contributed by Amit Khandelwal.


Output:

Found pattern at index 10

Time Complexity: O(m+n)

Space Complexity: O(m)

Please refer complete article on KMP Algorithm for Pattern Searching for more details!



Similar Reads

C# Program for Naive algorithm for Pattern Searching
Write a C# program for a given text string with length n and a pattern with length m, the task is to print all occurrences of the pattern in text.Note: You may assume that n &gt; m. Examples: Input: text = “THIS IS A TEST TEXT”, pattern = “TEST”Output: Pattern found at index 10 Input: text = “AABAACAADAABAABA”, pattern = “AABA”Output: Pattern found
2 min read
C# - Perform Searching using Predefined Functions
Given an array, now our task is to perform searching an element in an array using predefined functions in C#. So, the best searching technique is Binary search and will search the given element in an array using predefined functions. Binary search is an efficient algorithm that will work only on sorted sets of elements. So if we want to use binary
3 min read
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortes
5 min read
C# Program for Block swap algorithm for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABl
4 min read
C# Program for Reversal algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example : Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array by 2 will make array Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. The first 3 methods to rotate an array by
3 min read
C# Program for Program for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. METHOD 1 (Using temp array) Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7 1) Store the first d elements in a temp array temp[] = [1,
5 min read
C# Program to Demonstrate the Example of LINQ Union() Method with StringComparer
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives a feature to .NET languages to create queries to retrieve data from the data source. Here in this article, we will demonstrate the example of the LINQ Union() method with the StringComparer. 1. Union() Method: This method is used to get the unique elements from th
2 min read
C# Program to Demonstrate the Example of an Array of Delegates
In C#, a delegate is an object which refers to a method or it is a reference type variable that can hold a reference to the methods. Delegates are similar to the C/C++ function pointer. It also provides a way that tells which method is to be called when an event is triggered. As the name suggests an array of delegates means declaring an array of de
3 min read
C# Program to Check Given Directory Exists or not
Given a directory, now our task is to check given directory exists or not. So to this task, we use the Exists() method of the Directory class. This method will return true if the given directory exists, otherwise false. Syntax: public static bool Exists (string? Mypath); Where, Mypath is a parameter of Exists() method of string type. It represents
2 min read
C# Program for Activity Selection Problem | Greedy Algo-1
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Example: Example 1 : Consider the following 3 activities sorted by finish time. start[] = {10, 12, 20}; finish[] = {20, 25, 30}; A person
2 min read
Article Tags :