您的位置:首页 > 其它

leetcode 28. Implement strStr()

2017-06-22 11:19 316 查看
原题;

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;
}

思路大概就是,两边进行循环比较就好,开始在边界的处理上出了点问题。

性能还是可以的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: