2131. Longest Palindrome by Concatenating Two Letter Words
Description
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 <= 105
words[i].length == 2
words[i]
consists of lowercase English letters.
Solutions
Solution 1: Greedy + Hash Table
First, we use a hash table \(\textit{cnt}\) to count the occurrences of each word.
Iterate through each word \(k\) and its count \(v\) in \(\textit{cnt}\):
-
If the two letters in \(k\) are the same, we can concatenate \(\left \lfloor \frac{v}{2} \right \rfloor \times 2\) copies of \(k\) to the front and back of the palindrome. If there is one \(k\) left, we can record it in \(x\) for now.
-
If the two letters in \(k\) are different, we need to find a word \(k'\) such that the two letters in \(k'\) are the reverse of \(k\), i.e., \(k' = k[1] + k[0]\). If \(k'\) exists, we can concatenate \(\min(v, \textit{cnt}[k'])\) copies of \(k\) to the front and back of the palindrome.
After the iteration, if \(x\) is not empty, we can also place one word in the middle of the palindrome.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of words.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|