Runtime: 0 ms, faster than 100.00% of C++ online submissions for Implement strStr().
Memory Usage: 9.4 MB, less than 87.77% of C++ online submissions for Implement strStr().
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0)
{
return 0;
}
vector<int> next = getNext(needle);
int i = 0;
int j = 0;
int hlen = haystack.size();
int nlen = needle.size();
while (i < hlen && j < nlen)
{
if (j == -1)
{
++i;
++j;
}
else if (haystack[i] == needle[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == needle.size())
{
return i - j;
}
else
{
return -1;
}
}
vector<int> getNext(string needle)
{
vector<int> next(needle.size());
next[0] = -1;
int i = 0;
int j = -1;
while (i < needle.size() - 1)
{
if (j == -1)
{
++i;
++j;
next[i] = j;
}
else if (needle[i] == needle[j])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}
};
leetcode记录28. Implement
最新推荐文章于 2024-06-04 16:34:54 发布
本文介绍了一种使用KMP算法在C++中实现strStr()函数的方法,该方法在在线提交中比100.00%的C++提交更快,内存使用也优于87.77%的提交。文章详细展示了如何通过计算next数组来提高字符串匹配的效率,并提供了完整的代码示例。
434

被折叠的 条评论
为什么被折叠?



