Longest Palindrome by Concatenating Two Letter Words LeetCode solution in C++

1
class Solution {
2
public:
3
int longestPalindrome(vector<string> &words) {
4
int count[26][26] = {};
5
int ans = 0;
6

7
for (auto w : words) {
8
int a = w[0] - 'a';
9
int b = w[1] - 'a';
10

11
if (count[b][a]) {
12
ans += 4;
13
count[b][a]--; // decrement the count as we found mirror word
14
} else
15
count[a][b]++; // increment the current word count if we not find any
16
// mirror word
17
}
18

19
for (int i = 0; i < 26; i++) {
20
if (count[i][i]) {
21
ans += 2;
22
break;
23
}
24
}
25

26
return ans;
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0