You are given an array of strings words. Each element of words consists of two lowercase English letters.
Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.
Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.
A palindrome is a string that reads the same forward and backward.
Example 1:
Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created.
Example 2:
Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created.
Example 3:
Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx".
Constraints:
1 <= words.length <= 105words[i].length == 2words[i] consists of lowercase English letters.class Solution {
public:
int longestPalindrome(vector<string>& words) {
int res=0;
vector<string> symm;
unordered_map <string, int> m;
for(auto w: words){
string rev=w;
reverse(rev.begin(), rev.end());
if(m[rev]) // reverse found
m[rev]--, res+=4;
else {
m[w]++; // No reverse occurance
if(rev==w) // check if potential symm pt
symm.push_back(w);
}
}
// find a single unpaired symmetry pt
for(auto e: symm)
if(m[e])
return res+2;
return res;
}
};class Solution {
public int longestPalindrome(String[] words) {
Map<String, Integer> map = new HashMap<>();
int count = 0;
for (String w : words) {
String rev = w.charAt(1) + "" + w.charAt(0);
if (map.containsKey(rev)) {
map.put(rev, map.get(rev) - 1);
if (map.get(rev) == 0)
map.remove(rev);
count += 2;
} else
map.put(w, map.getOrDefault(w, 0) + 1);
}
// System.out.println(map);
for (String w : map.keySet()) {
String rev = w.charAt(1) + "" + w.charAt(0);
if (w.equals(rev)) {
count++;
break;
}
}
return count * 2;
}
}class Solution {
public int longestPalindrome(String[] words) {
int[][] freq = new int[26][26];
for (String w : words)
freq[w.charAt(0) - 'a'][w.charAt(1) - 'a']++;
int usedWords = 0, unusedPals = 0;
for (int i = 0; i < 26; i++) {
// System.out.println((char)('a'+i)+Arrays.toString(freq[i]));
int oddPair = freq[i][i] % 2;
unusedPals += oddPair;
usedWords += freq[i][i] - oddPair;
freq[i][i] = 0;
}
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
usedWords += Math.min(freq[i][j], freq[j][i]);
if (unusedPals > 0)
usedWords++;
return usedWords * 2;
}
}