标签:
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