【字符串】B032 构造 K 个回文字符串(利用性质)

一、题目描述

Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s.

Return True if you can use all the characters in s to construct k palindrome strings or False otherwise.

Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"

方法一:考察回文串的特性

  • 对于单个字符串来说:当出现次数为奇数的字符 >=2 个,就构不成回文串了,即 odd 需要满足 odd <= 1
  • 所以当要构成 k 个回文串时,奇数字符必须 odd <= k 个,即至少不大于 k 个。
    • 需满足:k <= s.length();
class Solution {
    public boolean canConstruct(String s, int k) {
        if (s.length() < k)
            return false;
        char[] cs = s.toCharArray();
        int odd = 0, n = s.length(), m[] = new int[26];
        for (char c : cs)
            m[c-'a']++;
        for (int i : m) if ((i & 1) == 1) {
            odd++;
        }
        return odd <= k;
    }
}

复杂度分析

  • 时间复杂度: O ( N ) O(N) O(N)
  • 空间复杂度: O ( 1 ) O(1) O(1)

你可能感兴趣的:(#,字符串)