实现strStr()——python解决

早过忘川 提交于 2020-02-13 02:09:49

题目描述:

解决代码如下:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        lh = len(haystack)
        ln = len(needle)
        if ln == 0:
            return 0    
        if lh == 0 or lh < ln:
            return -1
        i = 0
        while(i<=lh-ln):
            if haystack[i] == needle[0]:
                if haystack[i:i+ln] == needle:
                    return i
                else:
                    i = i+1
            else:
                i += 1
        return -1

提交结果:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!