-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathKMP.cs
72 lines (62 loc) · 2.18 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
namespace Advanced.Algorithms.String;
/// <summary>
/// Knuth–Morris–Pratt(KMP) string search implementation.
/// </summary>
public class Kmp
{
/// <summary>
/// Returns the start index of first appearance
/// of pattern in input string.
/// Returns -1 if no match.
/// </summary>
public int Search(string input, string pattern)
{
var matchingInProgress = false;
var matchIndex = new int[pattern.Length];
var j = 0;
//create match index of chars
//to keep track of closest suffixes in pattern that form prefix of pattern
for (var i = 1; i < pattern.Length; i++)
//prefix don't match suffix anymore
if (!pattern[i].Equals(pattern[j]))
{
//don't skip unmatched i for next iteration
//since our for loop increments i
if (matchingInProgress) i--;
matchingInProgress = false;
//move back j to the beginning of last matched char
j = matchIndex[j == 0 ? 0 : j - 1];
}
//prefix match suffix so far
else
{
matchingInProgress = true;
//increment index of suffix
//to prefix index for corresponding char
matchIndex[i] = j + 1;
j++;
}
matchingInProgress = false;
//now start matching
j = 0;
for (var i = 0; i < input.Length; i++)
if (input[i] == pattern[j])
{
matchingInProgress = true;
j++;
//match complete
if (j == pattern.Length) return i - pattern.Length + 1;
}
else
{
//reduce i by one so that next comparison won't skip current i
//which is not matching with current j
//since our for loop increments i
if (matchingInProgress) i--;
matchingInProgress = false;
//jump back to closest suffix with prefix of pattern
if (j != 0) j = matchIndex[j - 1];
}
return -1;
}
}