o(m*n)->o(m+n)
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
void getNext(int* next, const string& s) {
int j = 0;//前缀的末尾
next[0] = 0;//第一个字符没有最长相等前后缀,规定为0
for(int i = 1; i < s.size(); i++) {
while (j > 0 && s[i] != s[j]) { // j要保证大于0,因为下面有取j-1作为数组下表的操作
j = next[j - 1]; // 从j-1对应的回退值开始回退
/*
为什么要让j跳回到next[j-1]
因为在模式串与文本串发生冲突时,我们就看前一位的next值,
并且跳回到以上一位next值作为下标的位置,只需要后面的部分重新匹配,,避免了一步一步移动
前缀和后缀也是如此,当发生冲突,也是要 从next[j-1]对应的值作为下标,重新匹配后面的部分
*/
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {//如果没有模式串返回0
return 0;
}
int next[needle.size()];//创建以模式串长度为空间大小的next数组
getNext(next, needle);
int j = 0;//模式串的编码
for (int i = 0; i < haystack.size(); i++) {//遍历文本串
while(j > 0 && haystack[i] != needle[j]) {//产生冲突
j = next[j - 1]; // 这里要找j前一位的对应的回退位置了
}
if (haystack[i] == needle[j]) {//不产生冲突
j++;
}
if (j == needle.size() ) {//j除了代表模式串的索引,还代表已经完全匹配的长度
return (i - needle.size() + 1);
}
}
return -1;
}
};
int main(){
Solution sl;
int rs;
string haystack;
cin>>haystack;
string needle;
cin>>needle;
rs=sl.strStr(haystack,needle);
cout<<rs;
}