[LeetCode] Longest Palindrome by Concatenating Two Letter Words

2131. Longest Palindrome by Concatenating Two Letter Words

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int longestPalindrome(vector<string>& words) {
int cache[26][26]{0,}, res(0), op(INT_MAX - 1), eq(0);
for(auto& w: words) {
++cache[w[0]-'a'][w[1]-'a'];
}
for(int i = 0; i < 26; i++) {
eq |= cache[i][i] & 1;
res += cache[i][i] & op;
for(int j = i + 1; j < 26; j++) {
res += min(cache[i][j], cache[j][i]) << 1;
}
}

return (res + eq)<<1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/12/PS/LeetCode/longest-palindrome-by-concatenating-two-letter-words/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.