Count directly elements matching the parity check, do not prefilter and count what's been included. URL: https://leetcode.com/problems/construct-k-palindrome-strings/ Signed-off-by: Matej Focko <me@mfocko.xyz>
16 lines
460 B
C#
16 lines
460 B
C#
public class Solution {
|
|
public bool CanConstruct(string s, int k) {
|
|
if (s.Length <= k) {
|
|
// Can't construct more palindromes than characters, but when equal
|
|
// can construct palindrome from each character.
|
|
return s.Length == k;
|
|
}
|
|
|
|
var parities = new short[26];
|
|
foreach (var c in s) {
|
|
parities[c - 'a'] ^= 1;
|
|
}
|
|
|
|
return parities.Count(p => p != 0) <= k;
|
|
}
|
|
}
|