Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
1. 暴力比较,过慢,无法通过大数据集合
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int hLength = strlen(haystack);
int nLength = strlen(needle);
int ti;
if(nLength==0 )
return haystack;
for(int i=0;i<hLength; i++)
{
ti=i;
int j=0;
while(j< nLength && haystack[i]==needle[j])
{
i++;
j++;
if(j==nLength)
return (haystack+ti);
}
i=ti;
}
return NULL;
}
};
2. KMP算法
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!strlen(needle)) return haystack;
if(!strlen(haystack)) return NULL;
int nLength=strlen(needle);
vector<int> preFix(nLength);
compPrefix(needle,preFix,nLength);
return matchStr(haystack,needle,preFix);
}
void compPrefix(char *needle,vector<int> &prefix, int length)
{
if(length==0) return;
prefix[0]=-1;
int k=-1;//the number of longest match of the prefix and the postfix
for(int i=1;i<length;i++)
{
while(k>-1 && needle[k+1]!=needle[i])//try to further match. If failed, scan backward
{
k=prefix[k];
}
if(needle[k+1]==needle[i]) //further match succeed.
k++;
prefix[i]=k;
}
}
char *matchStr(char *haystack, char* needle, vector<int> &prefix)
{
int k=-1;//current match index
for(int j=0;j<strlen(haystack);j++)
{
while(k>-1 && haystack[j]!=needle[k+1])
k=prefix[k];
if(needle[k+1]==haystack[j])
k++;
if(k==strlen(needle)-1) return haystack+j-k;
}
return NULL;
}
};