QUESTION:
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.
思路来自ling-nc大佬. 构建哈希表,统计每个单词的出现次数。
对于每个单词,检查其逆序是否存在于哈希表中,如果存在,则可以形成一个回文串,更新结果并减少对应的计数。
如果逆序不存在,则将该单词的计数增加。最后检查是否有可以作为中心的回文单词。
举例:
输入 [“lc”, “cl”, “gg”, “gg”]
“lc” 没有配对 → 存入 map: { “lc”: 1 }
“cl” 发现 “lc” 存在 → 成对使用 “lc”+”cl” → res += 4 → map 更新为 { “lc”: 0 }
“gg” 没有配对 → 存入 map: { “lc”: 0, “gg”: 1 }
第二个 “gg” 发现 “gg” 存在 → 成对使用 “gg”+”gg” → res += 4 → map: { “lc”: 0, “gg”: 0 }
接着检查哈希表中是否有可以作为中心的回文单词(即两个字母相同的单词),如果有,则可以增加2到结果中。第二部分:寻找中间部分(只能选一个对称字符串)
⚠️ 在这个例子中,”gg” 都被配完了,没剩下 → 不会加中间部分。
Code:
1 | from collections import defaultdict |
1 | function longestPalindrome(words: string[]): number { |