一看这道题,好像用kmp算法可以解决,可是思前想后都没有想起具体咋写,所以就上网找了教程。
教程链接:https://www.bilibili.com/video/av3246487?from=search&seid=10063401322647522802
(我明明当时考数据结构的时候背的滚瓜烂熟的,原理也搞得很清楚,全忘了,全还给老师了hhhh)
总之KMP就是找相同的前后缀,构建next数组,之后再匹配就好。
在学完教程之后就直接写代码就好了。
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "") return 0;
int l = needle.length();
int next[l + 1];
memset(next, 0, sizeof(next));
int i = 0, j = 1;
//构建next数组
while (j < l) {
if (needle[i] == needle[j]) {
next[j] = i + 1;
i++;
j++;
} else {
if (i == 0) {
j++;
} else {
i = next[i - 1];
}
}
}
//匹配
int l2 = haystack.length();
for (i = 0, j = 0; i < l2 && j < l; ) {
if (haystack[i] == needle[j]) {
i++;
j++;
} else {
if (j == 0) {
i++;
} else {
j = next[j - 1];
}
}
}
if (j != l) return -1;
return i - l;
}
};