class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
int m = haystack.size(), n = needle.size();
haystack = ' ' + haystack, needle = ' ' + needle;
vector<int> ne(n + 1);
for(int i = 2, j = 0; i <= n; i ++)
{
while(j && needle[i] != needle[j + 1]) j = ne[j];
if(needle[i] == needle[j + 1]) j ++;
ne[i] = j;
}
for(int i = 1, j = 0; i <= m; i ++)
{
while(j && haystack[i] != needle[j + 1]) j = ne[j];
if(haystack[i] == needle[j + 1]) j ++;
if(j == n) return i - n;
}
return -1;
}
};
LeetCode 28. 实现 strStr()
最新推荐文章于 2022-05-13 16:44:12 发布