记字符串匹配KMP算法
字符串匹配是一类经典的问题,在字符串s
中找出模式串t
第一个元素的下标,如果没有匹配到,则返回-1。此问题在leetcode中甚至归类为简单。
解决此问题最直接的思路是使用暴力解法,从第0个元素开始逐个比较元素,当字符不匹配时,s
的指针向前移动一位,不断重复。这种思路最简单且直接,但是无法通过测试用例,需要使用复杂度更低的方法。
KMP算法是经典的字符串匹配算法,代码量少,但是难以理解。其重点在于next
数组的构造。这里我直接记录下来。
using namespace std;
vector<int> get_next(string t) {
vector<int> next(t.size());
int i = 0, j = -1;
next[0] = -1;
while (i < static_cast<int>(t.length())) {
if (j == -1 || t[i] == t[j]) {
++i, ++j;
next[i] = j;
} else {
j = next[j];
}
}
return next;
}
int kmp(string s, string t) {
int i = 0, j = 0;
vector<int> next = get_next(t);
while (i < static_cast<int>(s.length()) &&
j < static_cast<int>(t.length())) {
if (j == -1 || s[i] == t[j]) {
++i, ++j;
} else {
j = next[j];
}
}
if (j == static_cast<int>(t.length())) {
return i - j;
}
return -1;
}