leetcode
leetcode 2751 ~ 2800
回文字符串的最大数量

回文字符串的最大数量

难度:

标签:

题目描述

You are given a 0-indexed string array words having length n and containing 0-indexed strings.

You are allowed to perform the following operation any number of times (including zero):

  • Choose integers i, j, x, and y such that 0 <= i, j < n, 0 <= x < words[i].length, 0 <= y < words[j].length, and swap the characters words[i][x] and words[j][y].

Return an integer denoting the maximum number of palindromes words can contain, after performing some operations.

Note: i and j may be equal during an operation.

 

Example 1:

Input: words = ["abbb","ba","aa"]
Output: 3
Explanation: In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
All strings in words are now palindromes.
Hence, the maximum number of palindromes achievable is 3.

Example 2:

Input: words = ["abc","ab"]
Output: 2
Explanation: In this example, one way to get the maximum number of palindromes is: 
Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
Both strings are now palindromes.
Hence, the maximum number of palindromes achievable is 2.

Example 3:

Input: words = ["cd","ef","a"]
Output: 1
Explanation: In this example, there is no need to perform any operation.
There is one palindrome in words "a".
It can be shown that it is not possible to get more than one palindrome after any number of operations.
Hence, the answer is 1.

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 100
  • words[i] consists only of lowercase English letters.

代码结果

运行时间: 62 ms, 内存: 17.1 MB


解释

方法:

题解的思路是首先合并所有字符串,计算所有字符的总频数,然后计算可以组成多少对字符(每对字符可以在回文中形成镜像对)。接着,对words中的每个字符串,检查是否有足够的字符对来构成回文(考虑每个字符串的一半长度所需的字符对)。如果可以,就将这个字符串计为可能转换为回文的字符串,否则跳过。这种方法的关键在于通过字符的全局交换来最大化回文字符串的数量,而不是局限于单个字符串内部的调整。

时间复杂度:

O(N + W log W)

空间复杂度:

O(W)

代码细节讲解

🦆
解题思路中为什么首先选择合并所有字符串再计算字符总频数?直接对每个字符串单独统计不可以吗?
合并所有字符串并计算总频数是为了最大化使用字符的可能性,使得可以构成的回文字符串数量最大。如果单独对每个字符串进行统计,可能会因为每个字符串内字符的局限性而无法形成更多的回文字符串。例如,一个字符串中有多余的字符,而另一个字符串中正缺少这些字符以形成回文。通过合并字符串并统计总频数,可以跨字符串调配这些字符,从而增加形成回文的潜在数量。
🦆
题解中提到每两个相同的字符可以形成一个字符对,这是否意味着任何字符数量的奇数部分都将被忽略不计?
是的,按照题解的逻辑,每两个相同的字符才能形成一个回文中的字符对。因此,任何字符的奇数部分在计算可以形成回文的字符对时会被剩余。这部分字符不能有效地用于形成字符对,因此在计算可用于构成回文的字符对的总数时会被忽略。然而,在实际构成回文字符串的过程中,这些奇数部分的字符可能用于位于回文中心的单个字符。
🦆
在计算可以构成回文的字符串时,为何选择对字符串长度进行排序?排序的目的是什么?
对字符串长度进行排序的目的是优先处理较短的字符串,因为它们需要较少的字符对来形成回文。这种策略确保了在有限的字符对资源下,能够尽可能多地构成回文字符串。从短到长处理字符串,可以在不耗尽字符对的情况下,最大化回文数量,因为处理长字符串时可能会由于字符对不足而无法构成回文,而较短的字符串更容易满足条件。

相关问题