码迷,mamicode.com
首页 > 编程语言 > 详细

28. Implement strStr()(KMP字符串匹配算法)

时间:2018-02-17 21:24:10      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:kmp   串匹配   not   http   amp   sel   else   cti   aaa   

 


Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

 

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1



 1 class Solution:
 2     def strStr(self, haystack, needle):
 3         """
 4         :type haystack: str
 5         :type needle: str
 6         :rtype: int
 7         """
 8         if needle ==‘‘:
 9             return 0
10         nexts=self.caclNext(needle)
11         ans = -1
12         i = 0
13         j = 0
14         while i < len(haystack):
15             if(j==-1 or haystack[i] == needle[j]):
16                 i += 1
17                 j += 1
18             else:
19                 j = nexts[j]
20             if j == len(needle):
21                 ans = i - len(needle)
22                 break
23         return ans
24 
25     def caclNext(self, p):
26         nexts = [0]*(len(p))
27         nexts[0] = -1
28         k = -1
29         j = 0
30         while j < len(p) - 1:
31             if k == -1 or p[j] == p[k]:
32                 k += 1
33                 j += 1
34                 nexts[j] = k
35             else:
36                 k = nexts[k]
37         return nexts

 

28. Implement strStr()(KMP字符串匹配算法)

标签:kmp   串匹配   not   http   amp   sel   else   cti   aaa   

原文地址:https://www.cnblogs.com/zle1992/p/8452163.html

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