-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathQuickBinaryFind.cs
51 lines (45 loc) · 1.19 KB
/
QuickBinaryFind.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
namespace JarInfectionScanner {
public class QuickBinaryFind {
public static int FindByteSubstring(byte[] largerArray, byte[] substring) {
int[] prefixTable = BuildPrefixTable(substring);
int i = 0; // index for largerArray
int j = 0; // index for substring
while (i < largerArray.Length) {
if (largerArray[i] == substring[j]) {
i++;
j++;
if (j == substring.Length) {
// Substring found
return i - j;
}
} else if (j > 0) {
j = prefixTable[j - 1];
} else {
i++;
}
}
// Substring not found
return -1;
}
private static int[] BuildPrefixTable(byte[] substring) {
int[] prefixTable = new int[substring.Length];
int length = 0;
int i = 1;
while (i < substring.Length) {
if (substring[i] == substring[length]) {
length++;
prefixTable[i] = length;
i++;
} else {
if (length != 0) {
length = prefixTable[length - 1];
} else {
prefixTable[i] = 0;
i++;
}
}
}
return prefixTable;
}
}
}