2131. Longest Palindrome by Concatenating Two Letter Words
T: O(n)
S: O(26*26)
```java
class Solution {
public int longestPalindrome(String[] words) {
int counter[][] = new int[26][26];
int result = 0;
for (String w : words) {
int a = w.charAt(0) - 'a';
int b = w.charAt(1) - 'a';
if (counter[b][a] > 0) { // find pair! add 4
result += 4;
counter[b][a]--; // remove this one
} else {
counter[a][b]++;
}
}
for (int i = 0; i < 26; i++) {
if (counter[i][i] > 0) { // only one same can count to 2
result += 2;
break;
}
}
return result;
}
}
/**
T: O(n)
S: O(26*26)
["dd","aa","bb","dd","aa","dd","bb","dd","aa","cc","bb","cc","dd","cc"]
cc 0 4 x
bb 0 4
aa 1 4
dd 1. 8
20 + 2
*/
```
Last updated