[字符串匹配、KMP]Implement strStr()

一、题目

Implement strStr().

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

 

二、分析

很容易想出O(M*N)的算法,也很容易实现。原串S,模式串P,利用Python中[i:j]方法, 在原串中匹配长度为len(p)的元素。若匹配,返回头;否则向右移。这样复杂度是O(M*N)

最快的是KMP,是O(M+N),看了一下午只看懂了个大概。不再用大块时间看了,早上零星时间吧,毕竟时间太紧张。

 

三、代码

1.O(M*N)

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

 

posted @ 2015-10-28 11:05  面包包包包包包  阅读(112)  评论(0编辑  收藏  举报