leetcode-28-Implement strStr()

题目描述:
Implement  strStr() .
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
int strStr(string haystack, string needle) 
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1

要完成的函数:
int strStr(string haystack, string needle)

代码:
int strStr(string haystack, string needle) 
    {
        if(needle.size()==0&&haystack.size()!=0)
            return 0;
        else if(needle.size()!=0&&haystack.size()==0)
            return -1;
        else if(needle.size()==0&&haystack.size()==0)
            return 0;
        else
        {
            int changdu=haystack.size()-needle.size();// **
            for(int i=0;i<=changdu;i++) //**
            {
            	if(haystack.substr(i,needle.size())==needle)
                return i;
            }
            return -1;
        }
        
    }

注意事项:
1、边界情况的判定。haystack为空?needle为空?haystack比needle长度小?
2、haystack.substr(x,y),x为起始点index,y为长度,注意不可以让x和y超过haystack的限制
3、string的size不是int类型,估计为unsigned类型。比如haystack="",needle="a",当cout<<haystack.size()-needle.size()<<endl;的时候,得到的会是一堆乱码,这时候强制类型转换,cout<<int(haystack.size()-needle.size())<<endl;才会得到-1的结果,这点在//**那里体现出来了。笔者在第一次submit的时候也犯了这个错误。


注意事项:

1、边界情况的判定。haystack为空?needle为空?haystack比needle长度小?

2、haystack.substr(x,y),x为起始点index,y为长度,注意不可以让x和y超过haystack的限制。

3、string的size不是int类型,估计为unsigned类型。比如haystack="",needle="a",当cout<<haystack.size()-needle.size()<<endl;的时候,得到的会是很奇怪的数字,这时候强制类型转换,cout<<int(haystack.size()-needle.size())<<endl;才会得到-1的结果,这点在代码中//**体现出来了。

//各位老哥知道怎么调整博客的行间距吗?好像编辑器没有行间距的选项,


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值