Leetcode 3035. Maximum Palindromes After Operations

  • [Leetcode 3035. Maximum Palindromes After Operations](#Leetcode 3035. Maximum Palindromes After Operations)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的话因为可以任意交换,因此事实上要考察回文的最大个数,我们只需要统计所有单词当中字符出现的频次,看看他们能组成多少回文即可。

而这部分,我们只需要统计所有的字符频次当中pair的个数和独立元素的个数即可,且需要注意的是,如果独立元素不够用了,我们可以将成对的元素拆分为两个独立元素,即可满足使用需求。

另外,要使得能组成的回文尽可能的多,我们应该优先匹配较短的单词,这样才能够确保能够组成最多的回文。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maxPalindromesAfterOperations(self, words: List[str]) -> int:
        cnt = defaultdict(int)
        for w in words:
            for ch in w:
                cnt[ch] += 1
        odd, even = 0, 0
        for v in cnt.values():
            odd += v % 2
            even += v // 2

        ans = 0
        lengths = sorted([len(w) for w in words])
        for l in lengths:
            if l % 2 <= odd and l // 2 <= even:
                ans += 1
                odd -= l % 2
                even -= l // 2
            elif l % 2 > odd and l // 2 < even:
                ans += 1
                odd += 1
                even -= (l+1) // 2
        return ans

提交代码评测得到:耗时130ms,占用内存17.3MB。

相关推荐
Espresso Macchiato8 小时前
Leetcode 3568. Minimum Moves to Clean the Classroom
剪枝·广度优先遍历·leetcode medium·堆排·leetcode周赛452·leetcode 3568
Espresso Macchiato4 天前
Leetcode 3567. Minimum Absolute Difference in Sliding Submatrix
leetcode·leetcode medium·leetcode周赛452·leetcode 3567
Espresso Macchiato4 天前
Leetcode 3566. Partition Array into Two Equal Product Subsets
动态规划·leetcode medium·leetcode 3566·leetcode周赛452
Espresso Macchiato10 天前
Leetcode 3557. Find Maximum Number of Non Intersecting Substrings
动态规划·leetcode medium·leetcode 3557·leetcode双周赛157
Espresso Macchiato18 天前
Leetcode 3552. Grid Teleportation Traversal
广度优先遍历·leetcode medium·leetcode周赛450·leetcode 3552·堆排
Espresso Macchiato19 天前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Espresso Macchiato22 天前
Leetcode 3543. Maximum Weighted K-Edge Path
leetcode·leetcode medium·图遍历·leetcode 3543·leetcode双周赛156
Espresso Macchiato1 个月前
Leetcode 3532. Path Existence Queries in a Graph I
leetcode medium·dsu·leetcode 3532·leetcode周赛447·uf
Espresso Macchiato1 个月前
Leetcode 3523. Make Array Non-decreasing
leetcode··leetcode medium·leetcode 3523·leetcode周赛446
Tisfy3 个月前
LeetCode 0132.分割回文串 II:动态规划
leetcode·动态规划·字符串·题解·回文