leetcode28 实现strStr()

比较普通的思路是进行遍历,每次进行列表比对:

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

当然,更好的做法是使用KMP算法:https://www.zhihu.com/question/21923021

你可能感兴趣的:(算法面试题)