Leetcode#28: Implement strStr()

Leetcode#28: 求子串第一次出现在母串时的位置索引

  • 题目链接:https://leetcode.com/problems/implement-strstr/

  • 题目描述:已知母串haystack和子串needle,若查找成功,返回子串第一次出现在母串中时,母串的位置索引;否则返回-1

  • 思 路:首先判断子串是否为空,若为空,则位置索引为0;再判断子串的长度是否大于母串,若大于,则返回-1;从母串的第一个字母开始遍历,直到(母串长度-子串长度)的位置为止,当遇到与needle首字符相同的位置时,检查haystack从该位置开始的与needle长度相同的块,与needle是否相同。

C++实现如下:

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        //判断子串是否为空,若为空,返回0
        if(needle.empty())
        {
            return 0;
        }

        int len1 = haystack.size();
        int len2 = needle.size();
        if(len1 < len2)
        {
            return -1;
        }
        //遍历
        for(int i = 0; i <= len1 - len2; ++i)
        {
            int j = 0;
            for(j = 0; j < len2; ++j)
            {
                if(haystack[i + j] != needle[j])
                    break;
            }
            if(j == len2)
            {
                return i;
            }
        }
        return -1;


    }
};

python实现如下(方法一):

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0

        if len(haystack) < len(needle):
            return -1

        for i in range(len(haystack) - len(needle)+1):
            if haystack[i] == needle[0]:
                j = 1
                while j < len(needle) and haystack[i+j] == needle[j]:
                    j = j + 1
                if j == len(needle):
                    return i
        return -1

python实现如下(方法二):

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0

        if len(haystack) < len(needle):
            return -1

        for i in range(len(haystack) - len(needle) + 1):
            if haystack[i:i + len(needle)] == needle:
                return i
        return -1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值