28. Implement strStr()

Implement strStr().

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

AC代码:

class Solution(object):
    def strStr(self, haystack, needle):
        for i in xrange(len(haystack) - len(needle) + 1):
            if needle == haystack[i:len(needle)+i]:
                return i
        return -1

关键点在于想到和needle匹配的只需要查找前 len(haystack) - len(needle) + 1 个下标就可以了,因为后面的长度不够肯定不可能匹配。

你可能感兴趣的:(28. Implement strStr())