classSolution: defstrStr(self, haystack: str, needle: str) -> int: n,m=len(haystack),len(needle) i,j=0,0 while i < n and j < m: if haystack[i]==needle[j]: i+=1 j+=1 else: i=i-j+1 j=0 if j==m: return i-j else: return -1
思路1:📊 性能分析
提交结果
运行时间:0ms击败100.00%
内存消耗:19.01MB击败65.73%
复杂度验证
时间复杂度:O(n∗m)
空间复杂度:O(1)
思路2:RK算法
思路2:代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defstrStr(self, haystack: str, needle: str) -> int: n,m=len(haystack),len(needle) hash_p=hash(needle) for i inrange(n-m+1): hash_t=hash(haystack[i:i+m]) if hash_t!=hash_p: continue len_str=0 for j inrange(m): if haystack[i+j]!=needle[j]: break len_str+=1 if len_str==m: return i return -1
classSolution: defstrStr(self, haystack: str, needle: str) -> int: defgenerateNext(p:str): m = len(p) next = [0for _ inrange(m)] left = 0 for right inrange(1,m): while left > 0and p[left]!=p[right]: left=next[left-1] if p[left]==p[right]: left+=1 next[right]=left returnnext n,m=len(haystack),len(needle) if m == 0: return0 next=generateNext(needle) j =0 for i inrange(n): while j >0and haystack[i]!=needle[j]: j=next[j-1] if haystack[i]==needle[j]: j+=1 if j == m: return i-m+1 return -1
classSolution: defstrStr(self, haystack: str, needle: str) -> int: defHorspool(T:str,p:str)->int: n,m=len(T),len(p) if m == 0: return0 move={} for i inrange(m-1): move[p[i]]=m-1-i i = m-1 while i < n: k= m-1 while k >= 0and T[i-(m - 1 - k)]==p[k] : k-=1 if k < 0: return i - m + 1 else : i += move.get(T[i],m) return -1 return Horspool(haystack, needle)
classSolution: defstrStr(self, haystack: str, needle: str) -> int: defSunday(T: str, p: str) -> int: n, m = len(T), len(p) if m == 0: return0 # 构建位移表(记录每个字符在模式串中最右出现的位置) lastPos = {} for i inrange(m): lastPos[p[i]] = i i = 0 while i <= n - m: j = 0 # 从左到右比较 while j < m and T[i + j] == p[j]: j += 1 if j == m: return i # 失配,查看窗口后的下一个字符 if i + m < n: next_char = T[i + m] # 移动步数 = m - 该字符在模式串中最右位置(若不存在则为 -1) step = m - lastPos.get(next_char, -1) else: break i += step return -1 return Sunday(haystack, needle)