2131. Longest Palindrome by Concatenating Two Letter Words
QUESTION
2131. Longest Palindrome by Concatenating Two Letter Words
My Think
The idea comes from the brilliant Ling-nc.
We build a hash map to count the occurrences of each word.
For each word, we check whether its reverse exists in the hash map. If it does, they can form a palindrome pair — we update the result and decrease the corresponding count. If the reverse does not exist, we increment the count for the current word. Finally, we check if there's any palindromic word that can be used as the center of the palindrome.
Example:
-
Input: ["lc", "cl", "gg", "gg"]
-
"lc" has no pair → stored in the map: { "lc": 1 }
-
"cl" finds "lc" exists → use "lc" + "cl" as a pair → res += 4 → map updated to { "lc": 0 }
-
"gg" has no pair → stored in the map: { "lc": 0, "gg": 1 }
-
Second "gg" finds "gg" exists → use "gg" + "gg" as a pair → res += 4 → map becomes { "lc": 0, "gg": 0 }
Then we check whether the hash map contains any palindromic word (i.e., a word with two identical characters) that can be used as the center of the final palindrome string. If such a word exists, we can add 2 more to the result.
-
Finding a center word (can only pick one symmetric word) ⚠️ In this example, all "gg" words have been paired, so none is left → no center word is added.
Code
from collections import defaultdict
from typing import List
class Solution:
def longestPalindrome(self, words: List[str]) -> int:
count = defaultdict(int)
res = 0
for word in words:
if count[word[::-1]] > 0:
count[word[::-1]] -= 1
res += 4
else:
count[word] += 1
for key, value in count.items():
if key[0] == key[1] and value > 0:
res += 2
break
return resfunction longestPalindrome(words: string[]): number {
const count: Map<string, number> = new Map();
let res = 0;
for (const word of words) {
const reversed = word.split("").reverse().join("");
const reversedCount = count.get(reversed) ?? 0;
if (reversedCount > 0) {
count.set(reversed, reversedCount - 1);
res += 2 * word.length;
} else {
count.set(word, (count.get(word) ?? 0) + 1);
}
}
for (const [word, freq] of count.entries()) {
if (word === word.split("").reverse().join("") && freq > 0) {
res += word.length;
break; // 只能选一个居中的回文串
}
}
return res;
}贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
2131. Longest Palindrome by Concatenating Two Letter Words
LeetCode 2131. Longest Palindrome by Concatenating Two Letter Words — hash map approach to pair words with their reverses, plus a center check for palindromic words; for intermediate algorithm learners.
219.Existing duplicate elements II Hash table graphics
LeetCode 219. 存在重复元素 II 题解 — 使用哈希表与滑动窗口双指针解法,核心技巧是维护一个长度不超过 k+1 的窗口,在窗口内快速检测重复元素。适合正在刷 LeetCode 数组与哈希表题目的求职者或算法学习者。