Skip to content

Commit e1b634b

Browse files
committedDec 20, 2020
perf: implement-strstr
1 parent 96627de commit e1b634b

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed
 

‎str.implement-strstr.py

+41-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,45 @@ class Solution:
55
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。
66
"""
77
def strStr(self, haystack: str, needle: str) -> int:
8+
if not haystack and not needle:
9+
return 0
10+
11+
if len(haystack) < len(needle):
12+
return -1
13+
14+
origin_len = len(haystack)
15+
aim_len = len(needle)
16+
origin_idx = 0
17+
aim_idx = 0
18+
19+
while aim_idx < aim_len:
20+
# 判断是否结束
21+
if origin_idx > origin_len - 1:
22+
return -1
23+
# 如果匹配相等,则都前进1位
24+
if needle[aim_idx] == haystack[origin_idx]:
25+
origin_idx += 1
26+
aim_idx += 1
27+
else:
28+
# 查找下一个字符的位置
29+
next_char_at = origin_idx - aim_idx + aim_len
30+
# 如果下一个字符超出,则返回 -1
31+
if next_char_at < origin_len:
32+
# 在目标串中匹配下一个字符
33+
aim_last_idx = needle.rfind(haystack[next_char_at])
34+
# 没找到则再往后移一位
35+
if aim_last_idx == -1:
36+
origin_idx = next_char_at + 1
37+
# 找到了,则更新原串的下标
38+
else:
39+
origin_idx = next_char_at - aim_last_idx
40+
# 更新目标串
41+
aim_idx = 0
42+
else:
43+
return -1
44+
return origin_idx - aim_idx
45+
46+
def strStrByForce(self, haystack: str, needle: str) -> int:
847
if len(haystack) < len(needle):
948
return -1
1049
haystack_len = len(haystack)
@@ -21,4 +60,5 @@ def strStr(self, haystack: str, needle: str) -> int:
2160

2261

2362
so = Solution()
24-
print(so.strStr('abc', 'c'))
63+
print(so.strStr('abc', 'c'))
64+
# print('abc'[2])

0 commit comments

Comments
 (0)