classSolution(object): defmatch(self, haystack, i, needle): for k in xrange(len(needle)): if haystack[i + k] != needle[k]: returnFalse returnTrue
defstrStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ m, n = len(haystack), len(needle) for i in xrange(m - n + 1): if self.match(haystack, i, needle): return i return -1
classSolution(object): defstrStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ ifnot needle: return0 m, n = len(haystack), len(needle)
# pre-calculate `p` array p = [0] j = 0 for i in xrange(1, n): while j > 0and needle[i] != needle[j]: j = p[j - 1] if needle[i] == needle[j]: j = j + 1 p.append(j)
j = 0 for i in xrange(m): while j > 0and haystack[i] != needle[j]: j = p[j - 1] if haystack[i] == needle[j]: j += 1 if j == n: return i - n + 1 return -1
classSolution(object): defstrStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ ifnot needle: return0 m, n = len(haystack), len(needle) p = {x: i for i, x in enumerate(needle)} i = n - 1 while i < m: found = True for j in xrange(n): if haystack[i - j] != needle[n - 1 - j]: c = p.get(haystack[i - j], -1) new_i = i - j + n - 1 - c if new_i <= i: i += 1 else: i = new_i found = False break if found: return i - n + 1 return -1