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

时间:2022-05-08
本文章向大家介绍【 关关的刷题日记46】Leetcode 28. Implement strStr(),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

关关的刷题日记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)。