2131. Longest Palindrome by Concatenating Two Letter Words #1725
-
Topics: You are given an array of strings Create the longest possible palindrome by selecting some elements from Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return A palindrome is a string that reads the same forward and backward. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the longest possible palindrome that can be formed by concatenating selected two-letter words from a given list. Each word can be used at most once. The approach involves efficiently counting word frequencies and strategically using pairs of words to form the palindrome. Approach
Let's implement this solution in PHP: 2131. Longest Palindrome by Concatenating Two Letter Words <?php
/**
* @param String[] $words
* @return Integer
*/
function longestPalindrome($words) {
$freq = array();
foreach ($words as $word) {
if (isset($freq[$word])) {
$freq[$word]++;
} else {
$freq[$word] = 1;
}
}
$total = 0;
$has_center = false;
foreach ($freq as $word => $count) {
if ($word[0] == $word[1]) { // Check if the word is a palindrome
$pairs = intval($count / 2);
$total += $pairs * 4; // Each pair contributes 4 characters
if ($count % 2 == 1) {
$has_center = true;
}
} else {
$reversed = strrev($word);
if (isset($freq[$reversed]) && $word < $reversed) {
// Ensure each pair is processed once
$min = min($count, $freq[$reversed]);
$total += $min * 4; // Each pair contributes 4 characters
}
}
}
if ($has_center) {
$total += 2; // Add the center palindrome if possible
}
return $total;
}
// Example Test Cases
$test1 = ["lc","cl","gg"];
$test2 = ["ab","ty","yt","lc","cl","ab"];
$test3 = ["cc","ll","xx"];
echo longestPalindrome($test1) . "\n"; // Output: 6
echo longestPalindrome($test2) . "\n"; // Output: 8
echo longestPalindrome($test3) . "\n"; // Output: 2
?> Explanation:
This approach efficiently counts and pairs words to maximize the length of the resulting palindrome, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to determine the longest possible palindrome that can be formed by concatenating selected two-letter words from a given list. Each word can be used at most once. The approach involves efficiently counting word frequencies and strategically using pairs of words to form the palindrome.
Approach