【leetcode】(python) 28. Implement
2019-04-16 本文已影响0人
梦vctor
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
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
解题大意:
返回neelde在haystack中第一次出现的索引位置,如果不是haystack的一部分,则返回-1。
解题思路:
看完题目就想到了KMP算法,然后开始动手实现。后来发现python语言有专门的find()函数用来查找子串。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
这样就解决了,感觉异常简单。其实也可以用python的切片方法来实现find()的查找功能,值得注意的是遍历range(n)的遍历范围是0~n-1,这里i的范围为[0,m-n]闭区间。
时间复杂度是O(m)
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(haystack)
n = len(needle)
for i in range(m-n+1):
if haystack[i:i+n] == needle:
return i
return -1
参考:https://blog.csdn.net/fuxuemingzhu/article/details/79254558