LeetCode 1400. Construct K Palindrome Strings
原题链接在这里:https://leetcode.com/problems/construct-k-palindrome-strings/
题目:
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 <= 105sconsists of lowercase English letters.1 <= k <= 105
题解:
There are 2 conditions to fulfill.
One is k <= n. n = s.length(). We could break s into one single char String. But at most we could get n strings.
The other is the odd char count <= k. When there is a odd char, there must be another string containing it.
Time Complexity: O(n). n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public boolean canConstruct(String s, int k) { 3 int n = s.length(); 4 int [] count = new int[26]; 5 int odd = 0; 6 for(int i = 0; i < n; i++){ 7 int ind = s.charAt(i) - 'a'; 8 count[ind] ^= 1; 9 odd += count[ind] == 1 ? 1 : -1; 10 } 11 12 return odd <= k && n >= k; 13 } 14 }
浙公网安备 33010602011771号