您的位置:首页 > 其它

leetcode-Implement strStr()

2014-05-04 15:26 288 查看
问题描述:

mplement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
实现strStr()函数
直接上代码

class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(strcmp(haystack,"")==0 && strcmp(needle,"")==0)
        {
            return "";
        }
        if(strcmp(needle,"")==0)
        {
            return haystack;
        }
        if (strlen(haystack)<strlen(needle)) 
            return NULL;  
while(*haystack!='\0')
{
char *ptr1=haystack;
char *ptrNeedle = needle;
while(*ptrNeedle!='\0' && *ptr1!='\0')
{
if(*ptrNeedle == *ptr1)
{
ptrNeedle++;
ptr1++;
}
else
break;
}
if(ptrNeedle == NULL)
{
return haystack;
}
haystack++;
}
return NULL;
}
};

又是效率低,其中碰到了一个坑爹的问题,指针指向一个字符串,然后指针使劲++,最后判断指针指向了空,居然不能用while(ptr!=NULL),我too young,这个才是对的

while (*ptr!='\0')

再换一种高效的,好的代码就是别人一眼就能看懂的代码,想都不用想,上面这个写的太挫了,下面这个通过了leetcode,简单易懂

class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(strcmp(haystack,"")==0 && strcmp(needle,"")==0)
{
return "";
}
if(strcmp(needle,"")==0)
{
return haystack;
}
if (strlen(haystack)<strlen(needle))
return NULL;

for (int i = 0; i <= strlen(haystack) - strlen(needle); i++)
{
int j = 0;
for (; j < strlen(needle); j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == strlen(needle)) {
return &haystack[i];
}
}
return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息