File tree 1 file changed +63
-0
lines changed
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ # -*- coding: utf-8 -*-
2
+ # @Time : 2019/3/1 10:19
3
+ # @Author : xulzee
4
+
5
+ # @File : 28. Implement strStr().py
6
+ # @Software: PyCharm
7
+ from typing import List
8
+
9
+
10
+ class Solution :
11
+ def get_next (self , s : str ) -> List [int ]:
12
+ next_list = [- 1 ] * len (s )
13
+ i = 0
14
+ j = - 1
15
+ while i < len (s ) - 1 :
16
+ if j == - 1 or s [i ] == s [j ]:
17
+ i += 1
18
+ j += 1
19
+ next_list [i ] = j
20
+ else :
21
+ j = next_list [j ]
22
+ return next_list
23
+
24
+ def strStr (self , haystack : str , needle : str ) -> int :
25
+ next_list = self .get_next (haystack )
26
+ j = 0
27
+ i = 0
28
+ while i < len (haystack ) and j < len (needle ):
29
+ if j == - 1 or haystack [i ] == needle [j ]:
30
+ j += 1
31
+ i += 1
32
+ else :
33
+ j = next_list [j ]
34
+ if j == len (needle ):
35
+ return i - j
36
+ else :
37
+ return - 1
38
+ def strStr1 (self , haystack , needle ):
39
+ """
40
+ :type haystack: str
41
+ :type needle: str
42
+ :rtype: int
43
+ """
44
+ if not needle :
45
+ return 0
46
+
47
+ len_h = len (haystack )
48
+ len_n = len (needle )
49
+
50
+ for i in range (len_h ):
51
+ if i + len_n > len_h :
52
+ return - 1
53
+
54
+ if haystack [i ] == needle [0 ]:
55
+ if haystack [i :len_n + i ] == needle :
56
+ return i
57
+
58
+ return - 1
59
+
60
+ if __name__ == '__main__' :
61
+ haystack = "mississippi"
62
+ needle = "issip"
63
+ print (Solution ().strStr (haystack , needle ))
You can’t perform that action at this time.
0 commit comments