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

Leetcode 28 Implement strStr()

时间:2015-07-04 09:36:32      阅读:110      评论: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(n^2):以原字符串的index为指针,每次都检测接下来一段是否与子字符串一样。

class Solution:
    # @param {string} haystack
    # @param {string} needle
    # @return {integer}
    def strStr(self, haystack, needle):
        if haystack == needle == ‘‘:
            return 0
        if len(haystack) < len(needle):
            return -1
        for i in range(len(haystack)-len(needle)+1):
            if haystack[i:i+len(needle)] == needle:
                return i
        return -1

KMP算法 O(n) https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm

def str_str(string, substring)
   return if not string or not substring
   return 0 if substring == ‘‘
   
   # create failure function table
   pos = 2
   cnd = 0
   failure_table = [-1, 0]
   while pos < substring.length
     if substring[pos - 1] == substring[cnd]
       failure_table[pos] = cnd + 1
       pos += 1
       cnd += 1
     elsif cnd > 0
       cnd = failure_table[cnd]
     else
       failure_table[pos] = 0
       pos += 1
     end
   end

   m = i = 0
   while m + i < string.length
     if substring[i] == string[m + i]
       i += 1
       return m if i == substring.length
     else
       m = m + i - failure_table[i]
       i = failure_table[i] if i > 0
     end
   end
   -1
end

 

Leetcode 28 Implement strStr()

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4620180.html

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