第1.8节 实现strstr()

创建于20170313
原文链接:https://leetcode.com/problems/implement-strstr/

题目

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

题解

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        m=len(haystack)
        n=len(needle)
        if m < n:
            return -1
        elif m==0 or n==0:
            return 0
            
        for i in range(m-n+1):
            j=0
            while(j<n):
                if haystack[i+j] != needle[j]:
                    break
                else:
                    j+=1
            if j==n:
                return i
        return -1

解析

时间复杂度: O(N^2)

扩展

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 大梦一场的董二千先生 推开窗户,举起望远镜 眼底映出,一阵浓烟 前已无通路,后不见归途 敌视现实,虚构远方 东张西...
    _行到水穷处_阅读 467评论 0 0