[leetcode]#28. Implement strStr()
2017-11-17 09:34
411 查看
题目翻译
实现 strStr() 函数。该函数用于判断一个字符串 needle 是否是另一个字符串 haystack 的子串。如果是,则该函数返回 needle 在 haystack 中首次出现的地址;否则,返回-1。
扫描haystack,当遇到与needle首字符相同的位置时,检查haystack从该位置开始的与needle长度相同的块,与needle是否相同
鉴于这是一个模式匹配问题,我们可以考虑KMP算法。该算法对于任何模式和目标序列,都可以在线性时间内完成匹配查找(O(n+m)),而不会发生退化。这里不再细讲算法原理,只实现了代码。
实现 strStr() 函数。该函数用于判断一个字符串 needle 是否是另一个字符串 haystack 的子串。如果是,则该函数返回 needle 在 haystack 中首次出现的地址;否则,返回-1。
扫描haystack,当遇到与needle首字符相同的位置时,检查haystack从该位置开始的与needle长度相同的块,与needle是否相同
if not needle: return 0 for i in xrange(len(haystack) - len(needle) + 1): if haystack[i] == needle[0]: j = 1 while j < len(needle) and haystack[i+j] == needle[j]: j += 1 if j == len(needle): return i return -1
鉴于这是一个模式匹配问题,我们可以考虑KMP算法。该算法对于任何模式和目标序列,都可以在线性时间内完成匹配查找(O(n+m)),而不会发生退化。这里不再细讲算法原理,只实现了代码。
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 #generate next array, need O(n) time i, j, m, n = -1, 0, len(haystack), len(needle) next = [-1] * n while j < n - 1: #needle[k] stands for prefix, neelde[j] stands for postfix if i == -1 or needle[i] == needle[j]: i, j = i + 1, j + 1 next[j] = i else: i = next[i] #check through the haystack using next, need O(m) time i = j = 0 while i < m and j < n: if j == -1 or haystack[i] == needle[j]: i, j = i + 1, j + 1 else: j = next[j] if j == n: return i - j return -1
相关文章推荐
- leetcode 28. Implement strStr()
- [LeetCode]28. Implement strStr()
- LeetCode *** 28. Implement strStr()
- leetcode刷题记录-28. Implement strStr()
- 28. Implement strStr() leetcode Python new season 2016
- LeetCode 28. Implement strStr()
- LeetCode_Easy心得:28. Implement strStr()(C语言)
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- 2017.10.21 LeetCode - 13. Roman to Integer - 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode:28. Implement strStr()
- leetcode No28. Implement strStr()
- LeetCode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- 28. Implement strStr() LeetCode
- 【LeetCode】28. Implement strStr()
- leetcode 28. Implement strStr()
- leetCode 28. Implement strStr() 字符串
- Leetcode刷题记——28. Implement strStr(实现strStr)