Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
用KMP算法即可:
class Solution {
public:void get_next(char* T,int *next)
{
int i,j;
i=0;
j=-1;
next[0]=-1;
int lenT=strlen(T);
while(i<lenT)
{
if(j==-1||T[i]==T[j])
{
++i;
++j;
/* KMP原始算法
if(i<lenT)
next[i]=j;
*/
//KMP改进算法求next
if(i<lenT)
{
if(T[i]!=T[j])
next[i]=j;
else
next[i]=next[j];
}
}
else
j=next[j];
}
}
char *strStr(char *haystack, char *needle) {
int i = 0;
int j = 0;
int lenS=strlen(haystack),lenT=strlen(needle);
if(lenT==0)
return haystack;
int *next = new int[lenT];
get_next(needle,next);
while(i<lenS&&j<lenT)
{
if(j==-1||haystack[i]==needle[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j>=lenT)
return &haystack[i-lenT];
else
return NULL;
}
};