前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-28-Implement strStr()

leetcode-28-Implement strStr()

作者头像
chenjx85
发布2018-05-21 18:26:21
4440
发布2018-05-21 18:26:21
举报
文章被收录于专栏:chenjx85的技术专栏

题目描述:

Implement strStr().

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

Example 1:

代码语言:javascript
复制
Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

代码语言:javascript
复制
Input: haystack = "aaaaa", needle = "bba"
Output: -1

要完成的函数:

int strStr(string haystack, string needle)

代码:

代码语言:javascript
复制
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的时候也犯了这个错误。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 代码:
  • 注意事项:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档