假设我们有一个字符串列表,其中每个字符串包含两个字母“ A”和“ B”。我们有两个值a和b。我们必须找到可以形成的最大字符串数。我们最多可以使用多个“ A”,最多可以使用b个“ B”,而无需重复使用。
因此,如果输入像字符串= [“ AAABB”,“ AABB”,“ AA”,“ BB”] a = 4 b = 2,则输出将为2,因为我们可以使用4“ A “ s”和2个“ B” [[AABB],“ AA”]。
为了解决这个问题,我们将遵循以下步骤-
对:=一个新列表
对于字符串中的每个w,
A:= w中的“ A”数
B:= w的大小-A
在配对末尾插入一对(A,B)
ans:=一张(a,b)值为0的映射
对于成对的每个馅饼(A,B),
如果temp_a> = A而temp_b> = B,则
回答:= TEMP
rem:=馅饼(temp_a-A,temp_b-B)
temp [rem]:= temp [rem]的最大值(如果rem不存在,则为0)和(wc + 1)
temp:=来自ans的新映射
对于每对(temp_a,temp_b)和ans的值wc,执行
返回ans所有值列表的最大值
让我们看下面的实现以更好地理解-
class Solution:
   def solve(self, strings, a, b):
      pairs = []
      for w in strings:
         A = w.count("A")
         B = len(w) - A
         pairs.append((A, B))
      ans = {(a, b): 0}
      for A, B in pairs:
         temp = dict(ans)
         for (temp_a, temp_b), wc in ans.items():
            if temp_a >= A and temp_b >= B:
               rem = (temp_a - A, temp_b - B)
               temp[rem] = max(temp.get(rem, 0), wc + 1)
         ans = temp
      return max(ans.values())
ob = Solution()strings = ["AAABB", "AABB", "AA", "BB"]
a = 4
b = 2
print(ob.solve(strings, a, b))["AAABB", "AABB", "AA", "BB"], 4, 2
输出结果
2