|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * 1400. Construct K Palindrome Strings |
| 8 | + * |
| 9 | + * Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s. |
| 10 | + * Return True if you can use all the characters in s to construct k palindrome strings or False otherwise. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * Input: s = "annabelle", k = 2 |
| 14 | + * Output: true |
| 15 | + * Explanation: You can construct two palindromes using all characters in s. |
| 16 | + * Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b" |
| 17 | + * |
| 18 | + * Example 2: |
| 19 | + * Input: s = "leetcode", k = 3 |
| 20 | + * Output: false |
| 21 | + * Explanation: It is impossible to construct 3 palindromes using all the characters of s. |
| 22 | + * |
| 23 | + * Example 3: |
| 24 | + * Input: s = "true", k = 4 |
| 25 | + * Output: true |
| 26 | + * Explanation: The only possible solution is to put each character in a separate string. |
| 27 | + * |
| 28 | + * Example 4: |
| 29 | + * Input: s = "yzyzyzyzyzyzyzy", k = 2 |
| 30 | + * Output: true |
| 31 | + * Explanation: Simply you can put all z's in one string and all y's in the other string. Both strings will be palindrome. |
| 32 | + * |
| 33 | + * Example 5: |
| 34 | + * Input: s = "cr", k = 7 |
| 35 | + * Output: false |
| 36 | + * Explanation: We don't have enough characters in s to construct 7 palindromes. |
| 37 | + * |
| 38 | + * Constraints: |
| 39 | + * 1 <= s.length <= 10^5 |
| 40 | + * All characters in s are lower-case English letters. |
| 41 | + * 1 <= k <= 10^5 |
| 42 | + * */ |
| 43 | +public class _1400 { |
| 44 | + public static class Solution1 { |
| 45 | + public boolean canConstruct(String s, int k) { |
| 46 | + if (s.length() < k) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + Map<Character, Integer> map = new HashMap<>(); |
| 50 | + for (char c : s.toCharArray()) { |
| 51 | + map.put(c, map.getOrDefault(c, 0) + 1); |
| 52 | + } |
| 53 | + int count = 0; |
| 54 | + for (char c : map.keySet()) { |
| 55 | + if (map.get(c) % 2 == 1) { |
| 56 | + count++; |
| 57 | + } |
| 58 | + } |
| 59 | + return count <= k; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments