问题:判断haystack中needle子串首次出现位置
解决方案(python)
1. 首先判断子串是否为0,再进行初步筛选,最后给出答案,效率36ms。
def strStr(haystack, needle):
if(len(needle) == 0):
return 0
if(len(haystack)<len(needle)):
return -1
return haystack.find(needle)
2. 方法同上不进行筛选,效率为40ms。
3. 只利用find函数,效率达到32ms
return haystack.find(needle)
知识点
1. 字符串是否包含子串判断方法
1)find函数
2)index函数
2. 简写表达式
return a if a<b else b