想要看更加舒服的排版、更加准时的推送
关注公众号“不太灵光的程序员”
每日八点有干货推送,微信随时解答你的疑问
28 实现 strStr() python3
简单
字符串
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
KMP算法实现 字符串匹配算法:KMP
Knuth–Morris–Pratt(KMP)算法是一种改进的字符串匹配算法,它的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。它的时间复杂度是 O(m + n)O(m+n)。
但是从提交的用时来看,还是切片更快
# 11.8%
# 执行用时:64 ms
# 内存消耗:14.7 MB
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle: return 0
if not haystack: return -1
next_lst = self.buildNext(needle)
m = len(haystack)
n = len(needle)
i = j = 0
while j < n and i < m:
if j < 0 or haystack[i] == needle[j]:
i += 1
j += 1
else:
j = next_lst[j]
return i - j if i <= m and j == n else -1
def buildNext(self, needle):
j = 0
next_lst = [0] * len(needle)
next_lst[0] = t = -1
while j < len(needle) - 1:
if 0 > t or needle[j] == needle[t]:
j += 1
t += 1
next_lst[j] = t
else:
t = next_lst[t]
return next_lst
# 91.5%
# 执行用时:36 ms
# 内存消耗:13.8 MB
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle: return 0
ne_len, h_len = len(needle), len(haystack)
for start in range(h_len - ne_len + 1):
if haystack[start: start + ne_len] == needle:
return start
return -1
if __name__ == "__main__":
s = Solution()
haystack = "hello"
needle = "ll"
ret = s.strStr(haystack, needle)
print(ret)
haystack = "aaaaa"
needle = "bba"
ret = s.strStr(haystack, needle)
print(ret)
haystack = "aaaaabba"
needle = "bba"
ret = s.strStr(haystack, needle)
print(ret)