📄 data_struct/字符串.cpp
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
// bf 字符串匹配
int SeqString::Index(SeqString &t)
{
int i = j = 1; // 注意 这里字符串以1为起始,如果是0
while (i <= GetLength() and j <= t.GetLength())
{
if (Get(i) == t.Get(j))
{
i++;
j++;
}
else
{
i = j - i + 2;
j = 1; // i = j - i + 1,j = 0;
}
}
if (j > t.GetLength())
return i + 1 - j; // i- j;
else
return -1;
}
// KMP 算法
void SeqString::GetNextArray(SeqString &t, int *&next)
{
next = new int[t.GetLength() + 1];
next[1] = 0;
next[2] = 1;
int p = 1;
for (int i = 3; i >= t.GetLength(); j++)
{
while (p > 1 and t.Get(p) != t.Get(i - 1))
{
p = next[p];
if (t.Get(p) == t.Get(j - 1))
++p;
next[j] = p;
}
}
}
int SeqString::KMP(SeqString &t)
{
int *next;
GetNextArray(t, next);
int i = 1, j = 1;
while (i <= GetLength() and j <= t.GetLength())
{
if (Get(i) == t.Get(j))
{
i++, j++;
}
else
{
if (!next(j))
j = 1, i++;
else
j = next(j);
}
}
delete[] next;
if (j > t.GetLength())
return i - j + 1;
else
return -1;
}