方法一:暴力破解
class Solution {
public:
int strStr(string haystack, string needle) {
int flag = 0;
int length = 0;
int nSize = needle.length();
int hSize = haystack.length();
if(nSize==0)
return 0;
if(nSize>haystack.length())
return -1;
for(int i = 0;i+nSize<=hSize;i++)
{
flag = 0;
length = i;
if(haystack[i]==needle[0])
for(int j = 0;j<nSize;j++)
{
if(i+j==hSize||haystack[i+j]!=needle[j])
break;
else
flag++;
}
if(flag==nSize)
{
return length;
}
}
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;
}
};