1 Star 0 Fork 0

wd6/LeetCode-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
implement-strstr.cpp 1.52 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 9年前 . Update implement-strstr.cpp
// Time: O(n + k)
// Space: O(k)
// Wiki of KMP algorithm:
// http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
return KMP(haystack, needle);
}
int KMP(const string& text, const string& pattern) {
const vector<int> prefix = getPrefix(pattern);
int j = -1;
for (int i = 0; i < text.length(); ++i) {
while (j > -1 && pattern[j + 1] != text[i]) {
j = prefix[j];
}
if (pattern[j + 1] == text[i]) {
++j;
}
if (j == pattern.length() - 1) {
return i - j;
}
}
return -1;
}
vector<int> getPrefix(const string& pattern) {
vector<int> prefix(pattern.length(), -1);
int j = -1;
for (int i = 1; i < pattern.length(); ++i) {
while (j > -1 && pattern[j + 1] != pattern[i]) {
j = prefix[j];
}
if (pattern[j + 1] == pattern[i]) {
++j;
}
prefix[i] = j;
}
return prefix;
}
};
// Time: O(n * k)
// Space: O(k)
class Solution2 {
public:
int strStr(string haystack, string needle) {
for (int i = 0; i + needle.length() < haystack.length() + 1; ++i) {
if (haystack.substr(i, needle.length()) == needle) {
return i;
}
}
return -1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

搜索帮助