LeetCode第八天
28. Implement strStr()
在一个字符串中匹配一个子字符串,如果子字符串在该字符串中,则返回第一次出现的指针。很尴尬,python的string类型里面就有这个方法,find()。但是我觉得面试肯定不能这样,我就用了一个复杂度为O(n*m)的笨方法,就是遍历。但是还有一种更好的方法,KMP算法,时间复杂度为O(n+m)。接下来去了解一下,以后记录下来。
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ # return haystack.find(needle) # 感觉这种方法不是本题想测试的内容,应该是想来个KMP的,O(m+n) if len(haystack) < len(needle): # 这种方法的时间复杂度在O(n*m) return -1 elif len(haystack) == len(needle): if haystack == needle: return 0 else: return -1 else: for i in range(0, len(haystack)-len(needle)+1): if haystack[i:i + len(needle)] == needle: return i return -1

浙公网安备 33010602011771号