首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【 关关的刷题日记46】Leetcode 28. Implement strStr()

【 关关的刷题日记46】Leetcode 28. Implement strStr()

作者头像
WZEARW
发布2018-04-11 14:24:50
5980
发布2018-04-11 14:24:50
举报
文章被收录于专栏:专知专知

关关的刷题日记46 – Leetcode 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.

题目的意思是判断needle是否是haystack的子串,如果不是的话就返回-1,如果是的话就返回haystack中与needle匹配的子串的第一个字符的索引值。

方法1:遍历haystack,遇到与needle[0]相等的字符,就判断两个字符串接下来的needle.size()-1个字符是否匹配,匹配的话就返回haystack中第一个匹配字符的索引值。

class Solution {public:
    int strStr(string haystack, string needle) {
        if (needle.empty())
            return 0;
        for (int i = 0; i <= (int)(haystack.size() - needle.size()); ++i)
        {
            int j;
            for (j = 0; j < needle.size(); ++j)
            {
                if (haystack[j + i] != needle[j])
                    break;
            }
            if (j == needle.size())
                return i;
        }
        return -1;
    }};

方法2:用了substr。

class Solution {public:
    int strStr(string haystack, string needle) {
        if(needle.empty())
            return 0;
        for(int i=0; i<haystack.size(); i++)
        {
            if(haystack.substr(i,needle.size())==needle)
                return i;
        }
        return -1;
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-11-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档