LeetCode 1400. 构造 K 个回文字符串

题目描述

1400. 构造 K 个回文字符串

思路分析

解法一:计数判断(推荐)

核心思路

  • 统计字符频次中奇数次数的个数 odd
  • odd > k 或字符串长度 < k,则不可能。
  • 否则一定可构造。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示字符串长度。
  • 空间复杂度:O(1),字符集固定为 26。
class Solution {
    public boolean canConstruct(String s, int k) {
        if (s.length() < k) {
            return false;
        }

        int[] cnt = new int[26];
        for (int i = 0; i < s.length(); i++) {
            cnt[s.charAt(i) - 'a']++;
        }

        int odd = 0;
        for (int c : cnt) {
            if ((c & 1) == 1) {
                odd++;
            }
        }

        return odd <= k;
    }
}
func canConstruct(s string, k int) bool {
	if len(s) < k {
		return false
	}

	cnt := make([]int, 26)
	for i := 0; i < len(s); i++ {
		cnt[s[i]-'a']++
	}

	odd := 0
	for _, c := range cnt {
		if c&1 == 1 {
			odd++
		}
	}

	return odd <= k
}

相似题目

题目 难度 考察点
1400. 构造 K 个回文字符串 中等 计数
409. 最长回文串 简单 计数
266. 回文排列 简单 计数
267. 回文排列 II 中等 回溯
1177. 构建回文串检测 中等 前缀计数
本文作者:
本文链接: https://hgnulb.github.io/blog/2024/56345818
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!