以任意顺序拼接字符串以获取最大数量的 ‘AB‘

源内容(英文)

给定一个长度为 N 的字符串数组,允许以任意顺序连接它们。找出结果字符串中可能出现的 ‘AB‘ 的最大数量。

示例:

> 输入: N = 4, arr={ "BCA", "BGGGA", "JKA", "BALB" }

> 输出: 3

> 按 JKA + BGGA + BCA + BALB 的顺序连接它们,它将变成 JKABGGABCABALB,并且包含 3 次 ‘AB‘。

>

>

>

>

>

> 输入: N = 3, arr={ "ABCA", "BOOK", "BAND" }

> 输出: 2

方法:

预先计算每个字符串中 ‘AB‘ 的数量。重点关注当字符串重新排列时,跨越两个字符串的 ‘AB‘ 数量的变化。每个字符串中唯一重要的字符是它的首尾字符。

能够对结果产生贡献的字符串有:

  • 以 ‘B‘ 开头并以 ‘A‘ 结尾的字符串。
  • 以 ‘B‘ 开头但不以 ‘A‘ 结尾的字符串。
  • 不以 ‘B‘ 开头但以 ‘A‘ 结尾的字符串。

设 c1、c2 和 c3 分别为第 1、2 和 3 类字符串的数量。

  • 如果 c1 = 0,那么答案就是 min(c2, c3),因为只要两者都可用,我们就可以选取它们并连接起来。
  • 如果 c1 > 0 且 c2 + c3 = 0,那么答案是 c1 – 1,因为我们将它们按顺序一个接一个地连接。
  • 如果 c1 > 0 且 c2 + c3 > 0,并取 min(c2, c3) = p,首先将第 1 类字符串一个接一个地连接,产生额外的 c1 – 1 个 ‘AB‘,然后如果第 2 类和第 3 类都可用,则在当前结果字符串的开头添加第 3 类,并在当前结果字符串的末尾添加第 2 类。
  • 这样有 c1 – 1 + 2 = c1 + 1 个额外的 ‘AB‘,现在 c2 和 c3 各减少 1,p 变为 p – 1,然后只要两者都可用就同时选取第 2 类和第 3 类并添加它们,这样我们总共得到了 c1 + 1 + (p – 1) = c1 + p 个额外的 ‘AB‘。这意味着 c1 + min(c2, c3)。

下面是上述方法的实现:

C++


CODEBLOCK_cf9c5f34

Java


// Java implementation of above approach

import java.util.*;

class GFG

{

// Function to find maximum number of ABs

static int maxCountAB(String s[], int n)

{

// variable A, B, AB for count strings that

// end with ‘A‘ but not end with ‘B‘, ‘B‘ but

// does not end with ‘A‘ and ‘B‘ and ends

// with ‘A‘ respectively.

int A = 0, B = 0, BA = 0, ans = 0;

for (int i = 0; i < n; i++)

{

String S = s[i];

int L = S.length();

for (int j = 0; j < L – 1; j++)

{

// ‘AB‘ is already present in string

// before concatenate them

if (S.charAt(j) == ‘A‘ &&

S.charAt(j + 1) == ‘B‘)

{

ans++;

}

}

// count of strings that begins

// with ‘B‘ and ends with ‘A

if (S.charAt(0) == ‘B‘ && S.charAt(L – 1) == ‘A‘)

BA++;

// count of strings that begins

// with ‘B‘ but does not end with ‘A‘

else if (S.charAt(0) == ‘B‘)

B++;

// count of strings that ends with

// ‘A‘ but not end with ‘B‘

else if (S.charAt(L – 1) == ‘A‘)

A++;

}

// updating the value of ans and

// add extra count of ‘AB‘

if (BA == 0)

ans += Math.min(B, A);

else if (A + B == 0)

ans += BA – 1;

else

ans += BA + Math.min(B, A);

return ans;

}

// Driver Code

public static void main(String[] args)

{

String s[] = { "ABCA", "BOO

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/49109.html
点赞
0.00 平均评分 (0% 分数) - 0