28. Implement strStr()

题目: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值