-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbmh.cpp
More file actions
52 lines (42 loc) · 988 Bytes
/
bmh.cpp
File metadata and controls
52 lines (42 loc) · 988 Bytes
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
#include "project.h"
#include <unordered_map>
using namespace std;
int bmh(string T, string P);
unordered_map<char, int> getLastOccurrence(string str);
int bmh(string T, string P)
{
int tLength = T.length();
int pLength = P.length();
if (pLength <= tLength)
{
unordered_map<char, int> lastOccurence = getLastOccurrence(P);
int indexT = pLength - 1;
int indexP = indexT;
while (indexT <= tLength - 1)
{
if (T[indexT] == P[indexP])
{
if (indexP == 0)
return indexT;
else
{
indexT--;
indexP--;
}
}
else
{
indexT = indexT + pLength - min(indexP, lastOccurence[T[indexT]] + 1);
indexP = pLength - 1;
}
}
}
return -1;
}
unordered_map<char, int> getLastOccurrence(string str)
{
unordered_map<char, int> lastOccurence;
for (int index = 0; index < str.size(); ++index)
lastOccurence[str[index]] = index;
return lastOccurence;
}