题目要求
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
解题思路
1.暴力解题
暴力的方法当然是文本串中的每一个字符,将其作为首字符开始匹配模式串字符,每个字符都匹配上了,就返回当前
首字符的下标。代码略。
2.KMP算法
KMP算法是文本串中寻找模式串的高效算法,关键是最长相等前后缀长度的计算,即是next数组的设计与计算。
next数组中记录的是当前字符的最长相等前后缀的长度。当然在不同的具体实现中,next数组可能是不同的,
但作用都是使匹配索引回退到合适的位置而不是首字符。
代码
class Solution {
public:
int strStr(string haystack, string needle) {
int n = needle.size();
if (0 == n) return 0;
vector<int> next(n, 0);
getNext(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); ++i) {
while (j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
if (j == n - 1) {
return i - n + 1;
}
}
return -1;
}
void getNext(vector<int>& next, string needle) {
int j = -1;
next[0] = j;
for (int i = 1; i < needle.size(); ++i) {
while (j >= 0 && needle[i] != needle[j + 1]) {
j = next[j];
}
if (needle[i] == needle[j + 1]) {
j++;
}
next[i] = j;
}
}
};
今天主要学习KMP算法,我发现还是原生的直接记录模式串最长相等前后缀长度的next数组适合我。