-
Notifications
You must be signed in to change notification settings - Fork 0
/
bmh_algo.h
60 lines (55 loc) · 1.45 KB
/
bmh_algo.h
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
#pragma once
/// Boyer-Moore-Horspool Algorithm
/// Copyright (C) Flaviu Cibu. All rights reserved.
/// Created 27-may-2007
/// Updated 19-mar-2018
namespace stdext
{
namespace bmh
{
template <const unsigned jumpTableLength, typename C, typename Length>
void set_jump_table(Length* const jumpTable, const C* const pattern, const Length patternLength)
{
for (Length i = jumpTableLength - 1; i > 0; --i)
{
jumpTable[i] = patternLength;
}
jumpTable[0] = patternLength;
for (Length i = 0; i < patternLength; ++i)
{
jumpTable[pattern[i]] -= i + 1;
}
}
template <typename C, typename Length>
const C* find(const C* const pattern, const Length patternLength, const C* const text, const C* const textEnd, const Length* const jumpTable)
{
const C* const patternEnd = pattern + patternLength;
const C* patternPtr = patternEnd - 1;
for (const C* textPtr = text + patternLength - 1; textPtr < textEnd; )
{
if (*textPtr == *patternPtr)
{
do
{
if (patternPtr == pattern)
{
return textPtr;
}
}
while (*--textPtr == *--patternPtr);
const Length jump1 = Length(patternEnd - patternPtr);
const Length jump2 = jumpTable[*textPtr];
patternPtr = patternEnd - 1;
textPtr += (jump1 > jump2) ? jump1 : jump2;
}
else
{
textPtr += jumpTable[*textPtr];
textPtr += jumpTable[*textPtr];
textPtr += jumpTable[*textPtr];
}
}
return 0;
}
}
}