28. Implement strStr()

来源:互联网 发布:投资组合优化模型 编辑:程序博客网 时间:2024/06/04 01:38

题目:Implement strStr()

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

找一个字符串B在另一个字符串A中的起始位置。

需要注意NULL和""的区别。

char *str = NULL //申明字符串指针str并让它指向空地址
char *str = ""   //申明字符串指针str并让它指向空字符串
空字符串不是空地址,空地址就是0, 而且空字符串是有地址空间的。
       


比较笨的办法,就是两次循环,每个位置作为起始位置,开始判断是否相等,如果不相等那么就继续下一个循环,相等就继续比较。


代码:

int strStr(char* haystack, char* needle) {    int i=0,j=0;    int ret=0;    if(!haystack && !needle) return 0;        if(!haystack && needle) return -1;    if(haystack && !needle) return -1;        if(!(*haystack) && !(*needle) ) return 0;        if(!(*haystack) && *needle ) return -1;        if(*haystack && !(*needle) ) return 0;        //printf("The track1,haystack[i] is %c\n",*haystack);        while(haystack[i]!='\0')    {        int tmp=i;        int t=i;        ret=0;        //printf("Before: The haystack[i] is %c, the needle[ret] is %c\n",haystack[i],needle[ret]);                while(haystack[t]!=NULL && needle[ret]!=NULL && haystack[t]==needle[ret])        {            t++;            ret++;            continue;        }                //printf("After: The haystack[i] is %c, the needle[ret] is %c\n",haystack[i],needle[ret]);                if(needle[ret]==NULL)        {            ret=tmp;            return ret;        }        else if(haystack[t]==NULL)        {            return -1;        }        else        {            //printf("The track");            ret=-1;            i++;        }            }    return ret;    }


   













0 0
原创粉丝点击