【问题标题】:find number of anagrams for one array of string in respect to another array of string查找一个字符串数组相对于另一个字符串数组的字谜数
【发布时间】:2022-01-19 18:51:41
【问题描述】:

假设有两个字符串数组。一个数组命名为查询,另一个命名为字典。对于查询的每个字符串元素,您需要找出它在字典元素中存在多少个字谜,并将该数字推送到另一个数组。您的代码必须返回该数组,并且它的大小应该等于查询的大小(如预期的那样)。

我解决这个问题的方法是:

  1. 遍历查询和字典的每个元素(在嵌套循环中);
  2. 检查查询元素的长度是否等于字典的嵌套元素。如果是,那么我使用set(word)==set(st)(st 指的是字典)检查了它们是否具有相同的字符。

我的代码是这样的:

anagrams = list()
for word in query:
   ana = 0
   for st in dictionary:
      if(len(word)==len(st)):
          if(set(word)==set(st)):
             ana = ana + 1
   anagrams.append(ana)

这个逻辑给了我正确的结果,但它没有优化。结果,它超过了 10 秒的时间限制。查询和字典的长度都可以达到 10^15。

我的逻辑在 O(n^2) 时间内运行。有什么办法可以再优化一下代码吗?

【问题讨论】:

    标签: python arrays string anagram


    【解决方案1】:

    您可以使用 Python dictionaries 来加快速度:

    dict_sorted = {}
    
    for s in dictionary:  #  linear in terms of the size of `dictionary`
        sorted_s = sorted(s.lower())
        dict_sorted[sorted_s] = dict_sorted.get(sorted_s, 0) + 1
    
    anagrams = []
    
    for s in query:  #  linear in terms of the size of `query`
        sorted_s = sorted(s.lower())
        anagrams.append(dict_sorted.get(sorted_s, 0))
    

    使用collections.Counter 缩短内容:

    from collections import Counter
    
    dict_sorted = Counter([sorted(s.lower()) for s in dictionary])
    
    anagrams = [ dict_sorted.get(sorted(s.lower()), 0) for s in query ]
    

    【讨论】:

    • 我理解了使用字典部分的逻辑。但我无法使用集合获得逻辑。
    • @lonewolf collections.Counter 为我们完成了计数的工作,因此我们不必在循环中进行计数,只需给出一个列表,它会计算每个项目的出现次数。
    【解决方案2】:

    您的逻辑不正确,如果您测试字符集和长度,abbcaabc 将显示为字谜,它们不是。

    现在有一个 O(n) 时间,您可以使用 collections.Counter 计算字典中每个单词中的字符,然后转换为项目,然后将frozenset 本身在计数器中散列。然后只需检查查询的每个单词一次:

    from collections import Counter
    
    query = ['aabc', 'xyz', 'opq']
    dictionary = ['abac', 'baac', 'xyz', 'jkl', 'yxz']
    
    c = Counter(frozenset(Counter(w).items()) for w in dictionary)
    anagrams = [c[frozenset(Counter(w).items())] for w in query]
    

    输出:[2, 2, 0]

    【讨论】:

    • 您能详细说明一下吗?我不明白你的逻辑。
    • 为字典中的每个单词创建一个哈希。在这里,我使用了一个计数器,转换为frozenset。我计算字典中有多少哈希是相似的,为每个哈希制作一个计数字典。然后在读取查询时,我直接从计数字典中对到达词和她的计数进行哈希处理,即 O(1)。
    • @lonewolf 我刚刚看了另一个答案,基本上它做同样的事情,但使用不同的散列方法,这可能更有效,因为排序可能很昂贵。如果您仍然不明白,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2012-07-20
    • 2014-01-25
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多