class Solution {
public:
void get_next(vector<int>& next, const string& s)
{
int j=-1;
next[0] = j;
for(int i=1;i<s.size();i++)
{
while(j>=0&&s[j+1]!=s[i])
{
j = next[j];
}
if(s[j+1]==s[i])
{
j++;
}
next[i]=j;
}
}
int strStr(string haystack, string needle) {
vector<int> next(needle.size());
get_next(next, needle);
int j=-1;
for(int i=0;i<haystack.size();i++)
{
while(j>=0&&needle[j+1]!=haystack[i])
{
j = next[j];
}
if(needle[j+1]==haystack[i])
j++;
if(j==needle.size()-1)
return i-j;
}
return -1;
}
};
09-05
1573
06-29
05-28
2553
01-24
1825
04-15
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交