时间:2020-6-20
题目地址:https://leetcode-cn.com/problems/implement-strstr
题目难度:Easy
题目描述:
实现 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() 定义相符。
思路1:暴力破解
代码段1:一个用例超时
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle: return 0
if(len(haystack) < (len(needle))): return -1
temp, index, result = needle[0], 0, []
for i, x in enumerate(haystack):
if x == temp:
result.append(i)
print(result)
for o in result:
t, _ = o, True
for j in needle:
if t <= len(haystack) - 1:
if j == haystack[t]:
t += 1
else:
_ = False
else:
_ = False
if(_ == True):
return o
return -1
总结:
- 晚上8点写的,今天出去了一趟,太累了,脑子根本不动,基于测试用例编程,写了好几次,明天继续整吧,思路不清晰的时候果然不能写代码
思路2:使用切片
代码段2:通过
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
L, n = len(needle), len(haystack)
for start in range(n - L + 1):
if(haystack[start: start + L] == needle):
return start
return -1
总结:
- 时间复杂度O((N-L)L),将每个长度为L的同needle进行比较
思路3:使用双指针
只有和目标串第一位相同的才进行比较
代码段3:通过
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
L, n = len(needle), len(haystack)
if L == 0: return 0
pn = 0
while pn < n - L + 1:
while pn < n - L + 1 and haystack[pn] != needle[0]:
pn += 1
curr_len = pL = 0
while pL < L and pn < n and haystack[pn] == needle[pL]:
pn += 1
pL += 1
curr_len += 1
if curr_len == L:
return pn - L
pn = pn - curr_len +1
return -1
总结:
- 时间复杂度O((N-L)L),将每个长度为L的同needle进行比较
后续优化:KMP算法
参见:https://leetcode-cn.com/problems/implement-strstr/solution/kmp-suan-fa-xiang-jie-by-labuladong/