- 题目描述
实现 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() 定义相符。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr - 用python 字符串操作函数,来求解
传送门,先了解python字符串函数https://www.runoob.com/python/python-strings.html
这里我们主要使用find(函数)
string.find(str, beg=0, end=len(string))
检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1;
根据题目要求,我们还需要添加一个如果空返回0的判定。代码如下:
def strStr(haystack, needle):
if haystack==None or needle==None:
return 0
else:
index = haystack.find(needle,0)
return index
hays_list = ["hello","aaaaa",""]
needle_list = ["ll","bba",""]
for hays,need in zip(hays_list,needle_list):
search_re = strStr(hays,need)
print(search_re)
这种方法执行用时32ms。下面想想不用内置函数如何解决这个问题。
- 3.使用KMP求解
def Index_KMP(haystack, needle): i = 0 j = 0 if len(needle) == 0: return 0 elif len(haystack) == 0: return -1 else: next = getnext(needle) while (i<len(haystack) and j <len(needle)): a = haystack[i] b = needle[j] if j == -1 or haystack[i] == needle[j]: i += 1 j += 1 else: j = next[j]-1 if j==len(needle): index = i-len(needle) return index else: return -1 def getnext(needle): i = 0 next_array = [0] * len(needle) next_array[0] = 0 j = -1 while(i<len(needle)-1): if(j == -1 or needle[i]==needle[j]): i += 1 j += 1 if needle[i]!=needle[j]: next_array[i]=j+1 else: next_array[i] = next_array[j] else: j = next_array[j] j = j-1 return next_array hays_list = ["aaabaaabc","aaaaa",""] needle_list = ["aaa","bba",""] for hays,need in zip(hays_list,needle_list): ##search_re = strStr(hays,need) search_re = Index_KMP(hays, need) print(search_re)
KMP这里的主要问题在于next函数。数据结构学的是伪代码,从1开始索引,转为正儿八经的0开始索引。改为KMP之后运行时间是68ms反而不如直接调用内置函数了,摊手手~
-
python没有NULL,且None不为空长度。
-
固定长度初始化list方法,[]*n,range(n),[for]