题目描述:
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
方法一:暴力求解
代码1:
//暴力求解
int strStr1(string haystack, string needle) {
int n1 = haystack.size(), n2 = needle.size();
if (n2 == 0)return 0;
for (int i = 0; i <= n1 - n2; i++) {
if (haystack.substr(i, n2) == needle)
return i;
}
return -1;
}
方法二:KMP算法
代码2:
//KMP算法
int strStr(string haystack, string needle) {
int n1 = haystack.size(), n2 = needle.size();
if (n2 == 0)return 0;
vector<int>pi(n2);
for (int i = 1, j = 0; i < n2; 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 < n1; i++) {
while (j > 0 && haystack[i] != needle[j])
j = pi[j - 1];
if (haystack[i] == needle[j])
j++;
if (j == n2)
return i - n2 + 1;
}
return -1;
}