28.实现 strStr()

92 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

题目描述:

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:

输入: haystack = "hello", needle = "ll" 输出: 2 示例 2:

输入: haystack = "aaaaa", needle = "bba" 输出: -1 说明: 当 needle 是空字符串时,我们应当返回0

题目解析

这个是个字符串匹配的问题,通俗的说就是看母字符串里面是否包含较短的字符串,我们可以转换为集合问题,从一个大的集合里面去找一个子集合,并确定其位置。这就好比有一个大的模具盒,然后我们拿一个产品依次在模具盒里做对照,如果形状和模具盒里的匹配并且大小匹配,就能够完整的嵌入到模具盒里面。

对于这个问题也一样,我们可以拿needle字符串去匹配haystack字符串,找出haystack字符串里有和needle字符串完全一样的一段字符串,获取到这段字符串的起始索引,按照这个思路代码就会变得很简单

index=haystack.find(needle)

这是python最简单的写法,当然我们也可以自己写算法去实现find()的功能

 for i in range(0, length1-length+1):
     if haystack[i:i + length] == needle:
         return i

完整代码

def strStr(haystack, needle):
    if not needle:
        return 0
    length = len(needle)
    length1 = len(haystack)
    if length > length1:
        return -1
    for i in range(0, length1 - length + 1):
        if haystack[i:i + length] == needle:
            return i
        if i == length1 - length and haystack[i:i + length] is not needle:
            return -1