【发布时间】:2020-09-03 10:17:44
【问题描述】:
问题: 给定一个字符串 s 和一个非空字符串 p,在 s 中找到 p 的字谜的所有起始索引。
解决方案:
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
LS, LP, S, P, A = len(s), len(p), 0, 0, []
if LP > LS:
return [] # an empty array
for i in range(LP):
S, P = S + hash(s[i]), P + hash(p[i])
if S == P:
A.append(0)
for i in range(LP, LS):
S += hash(s[i]) - hash(s[i - LP])
if S == P:
A.append(i-LP+1)
return A
这是我参考@junaidmansuri 的提交提出的解决方案。但是我从来没有在 Python 中使用过 hash(),我无法理解它在这个函数中的作用。
我一直在 Jupyter 中使用 hash(),并注意到 hash('abc') 产生的整数与 hash('bca') 不同。正是由于这个原因,如果字符串中字母的排列影响其哈希值,我不明白 S == P 怎么可能为真。
此外,我也看不到 S, P = S + hash(s[i]), P + hash(p[i]) 正在调用什么。这个序列是否将十个大整数加在一起以获得P 的值?真的很迷茫。
非常感谢任何花时间阅读本文并帮助我的人。
【问题讨论】:
-
您的算法不正确。在
S == P的情况下,您需要比较实际的子字符串。否则你可能还会遇到哈希冲突。
标签: python python-3.x algorithm hash