2131. Longest Palindrome by Concatenating Two Letter Words

• Hardness: $$\color{orange}\textsf{Medium}$$
• Ralated Topics: ArrayHash TableStringGreedyCounting

### 一、題目#

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 <= 10^5
• words[i].length == 2
• words[i] consists of lowercase English letters.

### 二、分析#

• 此題可以利用 HashTable 來記錄有多少配對成功。
• s[0] == t[1] && s[1] == t[0]，所以可以檢查 map.count(word[1] + word[0]) 是否有在。
• 特別注意當 s[0] == s[1] 的時候，可以單獨擺在中間對稱也能成立，但要注意配對過的不能算。

### 三、解題#

#### 1. Hash Table#

• Time complexity: $$O(n)$$
• Space complexity: $$O(n)$$
int longestPalindrome(vector<string>& words) {
unordered_map<string, int> paired;
unordered_set<string> twin;
int cnt = 0;
for (string& word : words) {
if (word[0] == word[1]) {
if (twin.count(word)) {
twin.erase(word);
cnt += 4;
} else {
twin.insert(word);
}
} else {
string rev = {word[1], word[0]};
if (paired.count(rev) && paired[rev] > 0) {
paired[rev]--;
cnt += 4;
} else {
paired[word]++;
}
}
}
return cnt + (!twin.empty() ? 2 : 0);
}