题目:实现strStr函数,给定2个字符串haystack和needle,返回needle在haystack中的位置,如果不在就返回NULL。
class Solution
{
public:
char *strStr(char *haystack, char *needle)
{
int len1=strlen(haystack),len2=strlen(needle);
if(len2==0)
return haystack;
int i=0,j=0;
int back=0;
while(i<len1)
{
if(*(haystack+i)==*(needle+j))
{
i++;
j++;
if(j==len2)
return haystack+i-j;
}//如果单位匹配
else
{
back++;
i=back;
j=0;
}//如果不匹配回溯到back位置。
}
return NULL;
}
};