在Python中使用Counter()查找最小字符删除量,以生成两个字符串的字谜

给定两个小写字符串,任务是使它们 相同字母异序词 .唯一允许的操作是从任何字符串中删除字符。找到要删除的最小字符数以使两个字符串都变位? 如果两个字符串以任何顺序包含相同的数据集,则调用字符串 字谜 .

null

例如:

Input : str1 = "bcadeh" str2 = "hea"
Output: 3
We need to remove b, c and d from str1.

Input : str1 = "cddgk" str2 = "gcd"
Output: 2

Input : str1 = "bca" str2 = "acb"
Output: 0

此问题已有解决方案,请参考 删除最少数量的字符,使两个字符串成为字谜 链接我们将使用python快速解决这个问题 计数器() 字典数据结构 十字路口 财产 设置 数据结构。方法很简单,

  1. 使用将每个字符串转换为字典数据结构 计数器(可调) 方法
  2. 计算两个字典中的键数(count1,count2)和两个字典中常用的键数。
  3. 如果找不到公用密钥,则意味着我们需要删除 count1+count2 两个字符串中的字符。
  4. 其他的 (最大值(count1,count2)–countCommon) 将是要删除的字符数

      # Function remove minimum number of characters so that
      # two strings become anagram
      from collections import Counter
      def removeChars(str1, str2):
      # make dictionaries from both strings
      dict1 = Counter(str1)
      dict2 = Counter(str2)
      # extract keys from dict1 and dict2
      keys1 = dict1.keys()
      keys2 = dict2.keys()
      # count number of keys in both lists of keys
      count1 = len (keys1)
      count2 = len (keys2)
      # convert list of keys in set to find common keys
      set1 = set (keys1)
      commonKeys = len (set1.intersection(keys2))
      if (commonKeys = = 0 ):
      return count1 + count2
      else :
      return ( max (count1, count2) - commonKeys)
      # Driver program
      if __name__ = = "__main__" :
      str1 = 'bcadeh'
      str2 = 'hea'
      print (removeChars(str1, str2))

      
      

      输出:

      3
      

      替代解决方案:

      1. 使用将每个字符串转换为字典数据结构 计数器(可调) 方法
      2. 从两个句子中找出共同的元素
      3. 将公共字典中的值相加,以获得公共元素的总数。

          # Function remove minimum number of characters so that
          # two strings become anagram
          from collections import Counter
          def removeChars(a, b):
          # make dictionaries from both strings
          c1 = Counter(a)
          c2 = Counter(b)
          # finding the common elements from both dictonary
          common = c1&c2
          value = 0
          # adding up the key from common dictionary in order
          # to get the total number of common elements
          for key in common:
          value = value + common[key]
          # returning the number of elements to be
          # removed to form an anagram
          return ( len (a) - 2 * value + len (b))
          # Driver program
          if __name__ = = "__main__" :
          str1 = 'bcadeh'
          str2 = 'hea'
          print (removeChars(str1, str2))

          
          

          输出:

          3
          
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享