leetcode28:实现strStr

思想:

将haystack按needle的长度进行分割,如果needle == haystack[i:i+len(needle)],则return i反之return -1

class Solution2(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        for i in xrange(len(haystack) - len(needle) + 1):
            if haystack[i : i + len(needle)] == needle:
                return i
        return -1

以上是大神的做题思路 

小菜鸟思路来也

1.判断needle是否为空。若是则return 0,反之跳转2

2.判断needle是否不在haystack中,若是则return -1,反之跳转3

3.判断needle是否和haystack相等,若是则return 0,反之跳转4

4.将haystack按needle长度分割,如果needle == haystack[i:i+len(needle)],则return i

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """

        if len(needle) == 0:
            return 0
        elif needle not in haystack:
            return -1
        else:
            if needle == haystack:
                return 0
            else:
                for i in range(0,len(haystack)-len(needle)+1):
                    if needle == haystack[i:i+len(needle)]:
                        return i

if __name__ == "__main__":
    print(Solution().strStr("a", ""))
    print(Solution().strStr("abababcdab", "ababcdx"))

感觉小菜鸟的我还是很有潜力的哟!!!!

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/82977798