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;
}
思路大概就是,两边进行循环比较就好,开始在边界的处理上出了点问题。
性能还是可以的。
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;
}
思路大概就是,两边进行循环比较就好,开始在边界的处理上出了点问题。
性能还是可以的。
相关文章推荐
- [LeetCode] 28. Implement strStr() ☆
- leetcode 28. Implement strStr()
- LeetCode | 28. Implement strStr()——寻找子串
- [Leetcode]28. Implement strStr()
- [leetcode]28. Implement strStr()
- leetcode 28. Implement strStr()
- Leetcode 28. Implement strStr()
- Leetcode -- 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode刷题记录-28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode_Easy心得:28. Implement strStr()(C语言)
- 【一天一道LeetCode】#28. Implement strStr()
- [leetcode]: 28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode:28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr() 三种解法