Leetcode 28 Implement strStr()
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 needle == '': return 0 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
http://blog.csdn.net/v_july_v/article/details/7041827
失配时,模式串向右移动的位数为:已匹配字符数 - 失配字符的上一位字符所对应的最大长度值
def str_str(string, 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