forked from The-Open-Source-Society/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
KMP.cs
89 lines (75 loc) · 2.1 KB
/
KMP.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
namespace KMP_matching
{
class Program
{
public static void calculateLps(string pattern, int[] lps)
{
int length = 0; // Length of the previous longest prefix suffix
int i;
lps[0] = 0;
i = 1;
// The loop calculates lps[i] for i = 1 to size - 1
while(i < pattern.Length)
{
if(pattern[i] == pattern[length])
{
length++;
lps[i] = length;
i++;
}
else // If (pattern[i] != pattern[len])
{
if(length != 0)
length = lps[length - 1];
else
{
lps[i] = 0;
i++;
}
}
}
}
public static void KMPSearch(string pattern, string text)
{
int sizePattern = pattern.Length;
int sizeText = text.Length;
int[] lps = new int[sizePattern];
int j = 0;
calculateLps(pattern, lps);
int i = 0;
while(i < sizeText)
{
if (pattern[j] == text[i])
{
j++;
i++;
}
if(j == sizePattern)
{
Console.WriteLine("Pattern found at " + Convert.ToString(i - j + 1));
j = lps[j - 1];
}
else if (i < sizeText && pattern[j] != text[i])
{
if(j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
public static void Main(String[] args)
{
string text = "namanchamanbomanamansanam";
string pattern = "aman";
KMPSearch(pattern, text);
Console.ReadLine();
}
}
}
/* Output
Pattern found at 2
Pattern found at 8
Pattern found at 17
*/