LeetCode 题解工作台

构造 K 个回文字符串

给你一个字符串 s 和一个整数 k 。请你用 s 字符串中 所有字符 构造 k 个 非空 回文串 。 如果你可以用 s 中所有字符构造 k 个回文字符串,那么请你返回 True ,否则返回 False 。 示例 1: 输入: s = "annabelle", k = 2 输出: true 解释: 可…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们先判断字符串 的长度是否小于 ,如果是,那么一定无法构造出 个回文串,可以直接返回 `false`。 否则,我们用一个哈希表或数组 统计字符串 中每个字符出现的次数。最后,我们只需要统计 中奇数次数的字符个数 ,如果 大于 ,那么一定无法构造出 个回文串,返回 `false`;否则,返回 `true`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 和一个整数 k 。请你用 s 字符串中 所有字符 构造 k 个非空 回文串 。

如果你可以用 s 中所有字符构造 k 个回文字符串,那么请你返回 True ,否则返回 False 。

 

示例 1:

输入:s = "annabelle", k = 2
输出:true
解释:可以用 s 中所有字符构造 2 个回文字符串。
一些可行的构造方案包括:"anna" + "elble","anbna" + "elle","anellena" + "b"

示例 2:

输入:s = "leetcode", k = 3
输出:false
解释:无法用 s 中所有字符构造 3 个回文串。

示例 3:

输入:s = "true", k = 4
输出:true
解释:唯一可行的方案是让 s 中每个字符单独构成一个字符串。

 

提示:

  • 1 <= s.length <= 105
  • s 中所有字符都是小写英文字母。
  • 1 <= k <= 105
lightbulb

解题思路

方法一:计数

我们先判断字符串 ss 的长度是否小于 kk,如果是,那么一定无法构造出 kk 个回文串,可以直接返回 false

否则,我们用一个哈希表或数组 cntcnt 统计字符串 ss 中每个字符出现的次数。最后,我们只需要统计 cntcnt 中奇数次数的字符个数 xx,如果 xx 大于 kk,那么一定无法构造出 kk 个回文串,返回 false;否则,返回 true

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 是字符串 ss 的长度;而 CC 是字符集大小,这里 C=26C=26

1
2
3
4
5
6
7
class Solution:
    def canConstruct(self, s: str, k: int) -> bool:
        if len(s) < k:
            return False
        cnt = Counter(s)
        return sum(v & 1 for v in cnt.values()) <= k
speed

复杂度分析

指标
时间complexity is O(n) because each character is counted once. Space complexity is O(1) since the hash table only stores up to 26 lowercase letters, independent of string length.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    They may ask how to handle s.length < k efficiently.

  • question_mark

    They might probe the logic behind counting odd-frequency characters.

  • question_mark

    They could ask why a greedy allocation ensures correctness in forming k palindromes.

warning

常见陷阱

外企场景
  • error

    Forgetting to return false when s.length < k, which immediately invalidates the construction.

  • error

    Miscounting odd-frequency characters or assuming even counts are irrelevant.

  • error

    Attempting to construct palindromes explicitly rather than reasoning with counts, wasting time and space.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Construct k palindrome strings with additional constraints, like each palindrome having equal length.

  • arrow_right_alt

    Determine the maximum k for which a given s can form exactly k palindromes.

  • arrow_right_alt

    Check if s can form k palindromes where each contains at least one specific character.

help

常见问题

外企场景

构造 K 个回文字符串题解:贪心·invariant | LeetCode #1400 中等