参考链接
- https://leetcode-cn.com/problems/implement-strstr/
- https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode-solution-ds6y/
题目描述
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
解题思路
可以用暴力解法,不会超时,也可以借助某些语言的便利,如python的find(),Java的indexOf()一行就可以解决。
当然,可以使用KMP算法,也就这么点用处了。不过官方题解使用了一个技巧,它将模式串needle和目标串haystack用特殊字符"#"拼接起来,将字符串匹配问题转化为前缀函数(next数组)的求解问题。
代码
暴力解法
class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0, j = 0; i + needle.size() <= haystack.size(); i ++)
{
if (haystack.substr(i, needle.size()) == needle)
{
return i;
}
}
return -1;
}
};
KMP算法
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
if (m == 0) {
return 0;
}
vector<int> pi(m);
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle[i] != needle[j]) {
j = pi[j - 1];
}
if (needle[i] == needle[j]) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = pi[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
};