
Sponsored
Sponsored
The first approach involves counting occurrences of each word and its reverse. If a word appears with its reverse, they can be directly paired to contribute to the palindrome length. Symmetrical words like 'gg' can be used optimally to form palindromes, with one potentially serving as a center if their count is odd.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storage of words and their counts.
1function longestPalindrome(words) {
2 const count = {};
3 let length = 0;
4 let middleUsed = false;
5
6 for (let word of words) {
7 count[word] = (count[word] || 0) + 1;
8 }
9
10 for (let word of Object.keys(count)) {
11 let rev = word[1] + word[0];
12 if (word === rev) { // Symmetric word
13 length += Math.floor(count[word] / 2) * 4;
14 if (count[word] % 2 === 1 && !middleUsed) {
15 length += 2;
16 middleUsed = true;
17 }
18 } else if (count[rev]) {
19 let pairs = Math.min(count[word], count[rev]);
20 length += pairs * 4;
21 delete count[rev]; // Mark reverse used
22 }
23 }
24
25 return length;
26}
27
28// Example usage:
29const words = ["lc", "cl", "gg"];
30console.log(longestPalindrome(words));
31The JavaScript solution uses an object for counting word frequencies, then iterates over it to compute the longest palindrome by checking symmetrical pairs and using mirrored pairs. It uses deletion in the object to prevent double-counting.
This approach involves creating a hash map to quickly check for the existence of a word's reverse in the input, allowing us to efficiently pair words or use symmetric words optimally. We calculate pairs and handle middle contributions by taking account of unsused symmetric words.
Time Complexity: O(n) with a constant factor given by alphabets.
Space Complexity: O(1) as the 26x26 map is constant in size.
public class Solution {
public int LongestPalindrome(string[] words) {
int[,] map = new int[26, 26];
int length = 0;
bool hasMiddle = false;
foreach (var word in words) {
int a = word[0] - 'a';
int b = word[1] - 'a';
if (map[b, a] > 0) {
length += 4;
map[b, a]--;
} else {
map[a, b]++;
}
}
for (int i = 0; i < 26; ++i) {
if (map[i, i] > 0) {
hasMiddle = true;
break;
}
}
return length + (hasMiddle ? 2 : 0);
}
public static void Main(string[] args) {
Solution sol = new Solution();
string[] words = { "lc", "cl", "gg" };
Console.WriteLine(sol.LongestPalindrome(words));
}
}
C#'s solution embraces array manipulation for fast pair matching and reverse existence checking, facilitating efficient palindrome construction via combined indexed element-wise operations on constants size arrays.