Skip to content

Commit 841ac13

Browse files
authored
Create longest-palindrome-by-concatenating-two-letter-words.cpp
1 parent b947ac2 commit 841ac13

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int longestPalindrome(vector<string>& words) {
7+
unordered_map<string, int> cnt;
8+
for (const auto& x : words) {
9+
++cnt[x];
10+
}
11+
int result = 0, remain = 0;
12+
for (const auto& [x, c] : cnt) {
13+
const string mirror(crbegin(x), crend(x));
14+
if (x == mirror) {
15+
result += c / 2;
16+
remain |= c % 2;
17+
} else if (x < mirror && cnt.count(mirror)) {
18+
result += min(c, cnt[mirror]);
19+
}
20+
}
21+
return result * 4 + remain * 2;
22+
}
23+
};

0 commit comments

Comments
 (0)