第一种,自己的方法:
int strStr(char* haystack, char* needle) {
if( *needle == '\0' )
return 0;
char *n1, *n2;
int count = 0, flag = 0;
while( *haystack != '\0' )
{
n1 = haystack;
n2 = needle;
while( *n1 == *n2 && *n1 != '\0' && *n2 != '\0' )
{
n1++;
n2++;
}
if( *n2 == '\0' )
{
flag = 1;
break;
}
haystack++;
count++;
}
if( flag == 1 )
return count;
else
return -1;
}
分析:时间为472ms
原因:可能是因为需要多次进行指针计算与取值(具体我也不是很清楚,猜的)
第二种:大神解法
int strStr(char* haystack, char* needle) {
int i,j,len1,len2;
len1 = strlen(haystack);
len2 = strlen(needle);
if(len2==0) return 0;
for(i=0,j=0; i< len1; i++)
{
if(needle[j] == haystack[i])
{
j++;
}
else
{
i = i-j;
j = 0;
}
if(j == len2)
{
return i+1-j;
}
}
return -1;
}
耗时0ms.