Leetcode—— 28.实现strStr()

28.实现strStr()

实现 strStr() 函数。

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

示例 1:

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

输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

用Sunday算法来求解。

什么是Sunday算法呢?

目标字符串:S

模式串:P

当前查询索引:i

待匹配字符串:now_str    为 S[ i : i+len(P) ]

每一次都从目标字符串中提取待匹配的字符串与模式串进行匹配:

如果匹配的话,就返回当前的 i 

不匹配的话,查看待匹配字符串的后一位字符c,判断这个字符c在不在模式串P中:

如果在的话,则 i = i + 偏移表 [ c ]

不在的话,则 i = i + len(P)

直到 i + len(P) > len(S) 循环结束。

偏移表

偏移表的作用是存储每一个模式串中出现的字符,在模式串中出现的最右位置到尾部的距离 + 1,如 bba:

b 的偏移位 :len(P) -1 = 2

a 的偏移位: len(P) -2 = 1

其他的偏移位为 : len(P)+ 1 = 4

举例

S: hello

P: ll

第一步:

  • i = 0
  • 待匹配字符串为:he
  • 发现 he != ll
  • 查看he后一位字符 l
  • l 在 P 中
  • 查询偏移表,l 的偏移位: len(P) = 2 - 1 = 1
  • i = 0 + 1 = 1

第二步:

  • idx =  1
  • 待匹配字符串:el
  • 因为 el != ll
  • 查看 el 后一位字符 l
  • l 在 P 中
  • 查询偏移表,l 的偏移位: len(P) = 2 - 1 = 1

i = 1 + 1 = 2

第三步:

  • idx = 2
  • 待匹配字符串:ll
  • 因为 ll == ll
  • 匹配,返回 2

时间复杂度

平均情况:O(n)

最坏情况:O(nm)

程序代码:

def find_p(haystack,needle):
    #计算偏移表
    def shift_s(s):
        dic = {}
        for i in range(len(s)-1,-1,-1):
            if not dic.get(s[i]):
                dic[s[i]] = len(s) - i
        dic['other'] = len(s) + 1
        # print(dic)
        return dic


    dic = shift_s(needle)
    h_len = len(haystack)
    n_len = len(needle)
    i = 0
    while i + n_len <= h_len:
        now_str = haystack[i:i+n_len]
        if now_str == needle:
            return i
        else:
            if i + len(needle) >= len(haystack):
                return -1
            next_s = haystack[i+n_len]
            if dic.get(next_s):
                i += dic[next_s]
            else:
                i += dic['other']

    return -1 if i + len(needle) >= len(haystack) else i


haystack = "hello"
needle = "ll"
print(find_p(haystack, needle))

  以上内容参考Leetcode的Tset大佬分析。

发布了246 篇原创文章 · 获赞 155 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/suxiaorui/article/details/103096857