【问题标题】:Leet Code Question 438. Find All Anagrams in a String -- Need help understanding hash()Leet Code 问题 438. 查找字符串中的所有 Anagrams -- 需要帮助理解 hash()
【发布时间】: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


【解决方案1】:

试试这个:

def doit(s):
    return sum([hash(c) for c in s])

doit('abc')
doit('cab')
doit('acb')

你总是得到相同的结果。所以我在想基于这个你会理解算法是如何工作的。

希望这会有所帮助。

【讨论】:

  • 感谢您抽出宝贵时间回复。这有帮助!
猜你喜欢
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2013-12-27
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
相关资源
最近更新 更多