1. 题目来源
2. 题目解析
很明显,字符串模式匹配。可以采用 kmp
,也可以采用字符串哈希。在这就实现一个 kmp
即可。可参考:[kmp+模板] kmp模板
- 时间复杂度: O ( n + m ) O(n+m) O(n+m)。两字符串长度之和。
- 空间复杂度: O ( m ) O(m) O(m)
代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;
int n = haystack.size(), m = needle.size();
haystack = ' ' + haystack, needle = ' ' + needle;
vector<int> ne(m + 1);
for (int i = 2, j = 0; i <= m; 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 <= n; i ++) {
while (j && haystack[i] != needle[j + 1]) j = ne[j];
if (haystack[i] == needle[j + 1]) j ++;
if (j == m) return i - m;
}
return -1;
}
};