-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnuthMorrisPrattSearch.cs
More file actions
83 lines (72 loc) · 2.52 KB
/
Copy pathKnuthMorrisPrattSearch.cs
File metadata and controls
83 lines (72 loc) · 2.52 KB
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
namespace DA.Algorithms.Strings
{
public static class KnuthMorrisPrattSearch
{
public static int KnuthMorrisPratt_Search (string text, string pattern)
{
return KnuthMorrisPratt_Search (text.ToCharArray (), pattern.ToCharArray ());
}
public static int KnuthMorrisPratt_Search (char[] text, char[] pattern)
{
int index = 0;
int charCounter = 0;
int[] shiftArray = new int[pattern.Length + 1];
KnuthMorrisPratt_Preprocess (pattern, shiftArray);
while (index < text.Length)
{
while (charCounter >= 0 && text[index] != pattern[index])
{
charCounter = shiftArray[index];
}
++index;
++charCounter;
if (charCounter == pattern.Length)
return index - pattern.Length;
}
return -1;
}
public static int KnuthMorrisPratt_PatternCount (string text, string pattern)
{
return KnuthMorrisPratt_PatternCount (text.ToCharArray (), pattern.ToCharArray ());
}
public static int KnuthMorrisPratt_PatternCount (char[] text, char[] pattern)
{
int index = 0;
int charCounter = 0;
int patternCounter = 0;
int[] shiftArray = new int[pattern.Length + 1];
KnuthMorrisPratt_Preprocess (pattern, shiftArray);
while (index < text.Length)
{
while (charCounter >= 0 && text[index] != pattern[index])
{
charCounter = shiftArray[index];
}
++index;
++charCounter;
if (charCounter == pattern.Length)
{
++patternCounter;
charCounter = shiftArray[charCounter];
}
}
return patternCounter;
}
private static void KnuthMorrisPratt_Preprocess (char[] pattern, int[] shiftArray)
{
int index = 0;
int charCounter = 0;
shiftArray[index] = -1;
while (index < charCounter)
{
while (charCounter >= 0 && pattern[index] != pattern[charCounter])
{
charCounter = shiftArray[charCounter];
}
++index;
++charCounter;
shiftArray[index] = charCounter;
}
}
}
}