数据结构算法操作试题(C++/Python)——实现strStr()

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——实现strStr(),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 题目

leetcode 链接:https://leetcode-cn.com/problems/implement-strstr/submissions/

2. 解答

python: 36ms, 10.8MB

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not haystack and not needle: return 0
        if haystack == needle: return 0
        lenNeedle = len(needle)
        for i in range(len(haystack) - lenNeedle + 1):
            if haystack[i : i + lenNeedle] == needle:return i
        return -1

其他方法看 leetcode 链接 评论区~