码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-10-28 12:27:47      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

一、题目

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

 

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

标签:

原文地址:http://www.cnblogs.com/breada/p/4916689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!