Repository navigation
Expand file tree
/
Copy pathKMP.cs
More file actions
121 lines (114 loc) · 3.43 KB
/
Copy pathKMP.cs
File metadata and controls
121 lines (114 loc) · 3.43 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
Console.WriteLine(ArrayAndString.KMP.KMPSearch("cabcababcabcababca", "abcababc"));
*/
namespace Algorithm.ArrayAndString
{
class KMP
{
private static int[] NEXTSample(string pattern)
{
int[] tab = new int[pattern.Length];
tab[0] = -1;
for (int i = 1; i < pattern.Length; i++)
{
int j = tab[i - 1];
while (tab[i] != tab[j + 1] && j >= 0)
{
j = tab[j];
}
if (tab[i] == tab[j + 1]) tab[i] = j + 1;
else tab[i] = 0;
}
return tab;
}
public static int KMPSearchSample(string text, string pattern)
{
int pos = 0, iter = -1;
int[] tab = NEXTSample(pattern);
int count = 0;
for (int i = 0; i < text.Length; i++)
{
iter = i;
pos = 0;
while (iter < text.Length && pos < pattern.Length)
{
if (pattern[pos] == text[iter])
{
++pos; ++iter;
}
else
{
if (pos == 0) ++iter;
else pos = tab[pos - 1] + 1;
}
}
if (pos == pattern.Length && iter - i == pattern.Length) { ++count; }
}
return count;
}
//My implementation
public static int KMPSearch(string text, string pattern)
{
int[] helper = NEXT(pattern);
int i = 0, length = text.Length, count = 0;
for (; i < length; i++)
{
int pos = 0;
while (i < length)
{
if (text[i] == pattern[pos])
{
if (pos == pattern.Length - 1)
{
count++;
break;
}
i++;
pos++;
}
else
{
if (pos > 0)
{
//revision: 1/2/2013
pos = helper[pos - 1] - 1;
}
else
{
pos = 0;
}
i++;
}
}
}
return count;
}
private static int[] NEXT(string pattern)
{
int length = pattern.Length, i = 1, pos = 0;
int[] helper = new int[length];
while (i < length)
{
if (pattern[i] == pattern[pos])
{
pos++;
helper[i] = pos;
i++;
}
else
{
if (pos == 0)
{
helper[i] = pos;
i++;
}
else
{
pos--;
}
}
}
return helper;
}
}
}