Skip to content

Instantly share code, notes, and snippets.

@Nabid
Last active November 10, 2020 05:26
Show Gist options
  • Save Nabid/fde41e7c2b0b681ac674ccc93c1daeb1 to your computer and use it in GitHub Desktop.
Save Nabid/fde41e7c2b0b681ac674ccc93c1daeb1 to your computer and use it in GitHub Desktop.
C# implementation of KMP algorithm
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*
Reference: http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/
*/
namespace LeetCodeTest
{
class KMP
{
public List<int> KMPSearch(string text, string pattern)
{
int N = text.Length;
int M = pattern.Length;
if(N < M) return -1;
if(N == M && text == pattern) return 0;
if(M == 0) return 0;
int[] lpsArray = new int[M];
List<int> matchedIndex = new List<int>();
LongestPrefixSuffix(pattern, ref lpsArray);
int i = 0, j = 0;
while (i < N)
{
if (text[i] == pattern[j])
{
i++;
j++;
}
// match found at i-j
if (j == M)
{
matchedIndex.Add(i - j);
Console.WriteLine((i-j).ToString());
j = lpsArray[j - 1];
}
else if (i < N && text[i] != pattern[j])
{
if (j != 0)
{
j = lpsArray[j - 1];
}
else
{
i++;
}
}
}
return matchedIndex;
}
public void LongestPrefixSuffix(string pattern, ref int[] lpsArray)
{
int M = pattern.Length;
int len = 0;
lpsArray[0] = 0;
int i = 1;
while (i < M)
{
if (pattern[i] == pattern[len])
{
len++;
lpsArray[i] = len;
i++;
}
else
{
if (len == 0)
{
lpsArray[i] = 0;
i++;
}
else
{
len = lpsArray[len - 1];
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
KMP kmp = new KMP();
kmp.KMPSearch("bangladesh", "glade");
kmp.KMPSearch("ABABDABACDABABCABAB", "ABABCABAB");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment