Skip to content

Latest commit

 

History

History
128 lines (103 loc) · 2.93 KB

File metadata and controls

128 lines (103 loc) · 2.93 KB

中文文档

Description

Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.

 

Example 1:

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"

Example 2:

Input: s = "leetcode", k = 3
Output: false
Explanation: It is impossible to construct 3 palindromes using all the characters of s.

Example 3:

Input: s = "true", k = 4
Output: true
Explanation: The only possible solution is to put each character in a separate string.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
  • 1 <= k <= 105

Solutions

Python3

class Solution:
    def canConstruct(self, s: str, k: int) -> bool:
        if len(s) < k:
            return False
        counter = Counter(s)
        cnt = sum(1 for n in counter.values() if n % 2 == 1)
        return cnt <= k

Java

class Solution {
    public boolean canConstruct(String s, int k) {
        if (s.length() < k) {
            return false;
        }
        int[] counter = new int[26];
        for (char c : s.toCharArray()) {
            ++counter[c - 'a'];
        }
        int cnt = 0;
        for (int v : counter) {
            if (v % 2 == 1) {
                ++cnt;
            }
        }
        return cnt <= k;
    }
}

C++

class Solution {
public:
    bool canConstruct(string s, int k) {
        if (s.size() < k) return 0;
        vector<int> counter(26);
        for (char c : s) ++counter[c - 'a'];
        int cnt = 0;
        for (int v : counter)
            if (v % 2)
                ++cnt;
        return cnt <= k;
    }
};

Go

func canConstruct(s string, k int) bool {
	if len(s) < k {
		return false
	}
	counter := make([]int, 26)
	for _, c := range s {
		counter[c-'a']++
	}
	cnt := 0
	for _, v := range counter {
		if v%2 == 1 {
			cnt++
		}
	}
	return cnt <= k
}

...