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 Macchiato17 小时前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
Espresso Macchiato2 天前
Leetcode 3301. Maximize the Total Height of Unique Towers
leetcode·leetcode medium·leetcode双周赛140·leetcode 3301
Espresso Macchiato5 天前
Leetcode 3302. Find the Lexicographically Smallest Valid Sequence
leetcode medium·lcs·leetcode 3302·leetcode双周赛140·最大公共子序列
逝去的秋风1 个月前
【代码随想录训练营第42期 Day46打卡 - 回文问题 - LeetCode 647. 回文子串 516.最长回文子序列
leetcode·动态规划·回文
Espresso Macchiato2 个月前
Leetcode 3255. Find the Power of K-Size Subarrays II
leetcode·leetcode medium·leetcode 3255·leetcode 3254·leetcode周赛137
Espresso Macchiato2 个月前
Leetcode 3260. Find the Largest Palindrome Divisible by K
leetcode hard·回文·分类讨论·leetcode 3260·leetcode周赛411
Espresso Macchiato2 个月前
Leetcode 3240. Minimum Number of Flips to Make Binary Grid Palindromic II
leetcode·leetcode medium·回文·leetcode 3240·leetcode双周赛136
Espresso Macchiato2 个月前
Leetcode 3234. Count the Number of Substrings With Dominant Ones
排列组合·leetcode medium·容斥原理·leetcode 3234·leetcode周赛408
Espresso Macchiato3 个月前
Leetcode 3201. Find the Maximum Length of Valid Subsequence I
leetcode medium·leetcode题解·leetcode 3201·leetcode周赛404
闻缺陷则喜何志丹3 个月前
【马拉车 中心扩展】1745. 分割回文串 IV
c++·算法·leetcode·字符串·分割·回文·中心扩展