Chapter4-串
4.1 串类型的定义
n(n≥0)个字符的有限序列:
s
=
“
a
1
,
a
2
,
a
3
,
.
.
.
,
a
n
”
s = “a_1, a_2,a_3,...,a_n”
s=“a1,a2,a3,...,an”
其中,s称之为串名,
a
i
a_i
ai称之为串值,n为串长。
串包括了空串,字串和主串。

**需要注意的是:**字串中的每一个元素的位置与原本的串中的位置相同且相邻。
4.2 字符串模式匹配算法
4.2.1 暴力匹配
顾名思义,在匹配时非常暴力。时间复杂度极高。不在此多赘述。
4.2.2 KMP算法
这里直接找了B站上的一个博主介绍KMP算法。
最浅显易懂的 KMP 算法讲解
对于KMP算法主要考察的是next数组的求解,在这里用Kimi生成了个求解next数组并打印出next数组的代码供学习印证。
#include <iostream>
#include <vector>
#include <string>
// 计算next数组的函数
std::vector<int> computeNext(const std::string& pattern) {
int m = pattern.length();
std::vector<int> next(m, 0);
int j = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
return next;
}
int main() {
while (true)
{
std::string pattern;
std::cout << "Enter the pattern: ";
std::getline(std::cin, pattern);
std::vector<int> next = computeNext(pattern);
for (int i = 0; i < next.size(); ++i) {
std::cout << pattern[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < next.size(); ++i) {
std::cout << next[i] << " ";
}
std::cout << std::endl;
}
return 0;
}
1850

被折叠的 条评论
为什么被折叠?



