一:题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/b3d36daefff74d3ebcb332e6480b3d44.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5aSp5aSp5ZCR5LiK55qE6I-c6bih5p2w77yB77yB,size_14,color_FFFFFF,t_70,g_se,x_16)
二:上码
class Solution {
public:
void getNext(int *next,string s) {
int j = 0;
next[0] = 0;
for (int i = 1; i < s.size(); i++) {
while (j > 0 && s[i] != s[j]) {
j = next[j-1];
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
int next[needle.size()];
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];
}
if (haystack[i] == needle[j]) j++;
if (j == needle.size()) {
return (i-j+1);
}
}
return -1;
}
};
|