28. Implement strStr()

来源:互联网 发布:信义安所见乎翻译 编辑:程序博客网 时间:2024/05/16 03:19

Implement strStr().

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

翻译:手动实现strstr(字符串模式匹配 ---> KMP --->寻找next数组)

方法一:暴力求解,时间复杂度(O(mn))

class Solution(object):    def strStr(self, haystack, needle):      haystack_lenth = len(haystack)      needle_lenth   = len(needle)      if(haystack_lenth == 0 and needle_lenth == 0):        return 0      target_local = -1      for i in xrange(haystack_lenth):        if i > (haystack_lenth - needle_lenth):            break        tmp_i = i        match = 0        while(match < needle_lenth and tmp_i < haystack_lenth and haystack[tmp_i] == needle[match]):           tmp_i += 1           match += 1        if(match == needle_lenth):          target_local = i          break      return target_local