原题;
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
从字符串中找到最先出现匹配字符串needle的下标。上代码:
int strStr(char* haystack, char* needle) {
if(*needle=='\0')
return 0;
for(int n=0;*(haystack+n)!='\0';n++)
{
if(*(haystack+n)==*needle)
{
int flag=1;
for(int m=0;*(needle+m)!='\0';m++)
{
if(*(haystack+n+m)=='\0')
return -1;
if(*(haystack+n+m)!=*(needle+m))
{
flag=0;
break;
}
}
if(flag==1)
{
return n;
}
}
}
return -1;
}
思路大概就是,两边进行循环比较就好,开始在边界的处理上出了点问题。
性能还是可以的。