1400. Construct K Palindrome Strings #1118
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Topics: Given a string Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Jan 11, 2025
Replies: 1 comment 2 replies
-
We need to consider the following points: Key Observations:
Approach:
Let's implement this solution in PHP: 1400. Construct K Palindrome Strings <?php
/**
* @param String $s
* @param Integer $k
* @return Boolean
*/
function canConstruct($s, $k) {
// Step 1: If the length of s is less than k, return false
if (strlen($s) < $k) {
return false;
}
// Step 2: Count the frequency of each character
$freq = [];
for ($i = 0; $i < strlen($s); $i++) {
$char = $s[$i];
if (isset($freq[$char])) {
$freq[$char]++;
} else {
$freq[$char] = 1;
}
}
// Step 3: Count how many characters have an odd frequency
$oddCount = 0;
foreach ($freq as $count) {
if ($count % 2 != 0) {
$oddCount++;
}
}
// Step 4: If oddCount is greater than k, return false
if ($oddCount > $k) {
return false;
}
// Step 5: Otherwise, return true
return true;
}
// Test cases
var_dump(canConstruct("annabelle", 2)); // Output: true
var_dump(canConstruct("leetcode", 3)); // Output: false
var_dump(canConstruct("true", 4)); // Output: true
?> Explanation:
Time Complexity:
Edge Cases:
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
kovatz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We need to consider the following points:
Key Observations:
Palindrome Characteristics:
Necessary Conditions:
s
is less thank
, it's impossible to formk
strings, so returnfalse
.k
to formk
palindromes. This is because each palindrome can have at most one character with…