给你一个字符串数组 words 。 words 中每个元素都是一个包含 两个 小写英文字母的单词。
请你从 words 中选择一些元素并按 任意顺序 连接它们,并得到一个 尽可能长的回文串 。每个元素 至多 只能使用一次。
请你返回你能得到的最长回文串的 长度 。如果没办法得到任何一个回文串,请你返回 0 。
回文串 指的是从前往后和从后往前读一样的字符串。
示例 1:
输入:words = ["lc","cl","gg"]输出:6解释:一个最长的回文串为 "lc" + "gg" + "cl" = "lcggcl" ,长度为 6 。"clgglc" 是另一个可以得到的最长回文串。
示例 2:
输入:words = ["ab","ty","yt","lc","cl","ab"]
输出:8
解释:最长回文串是 "ty" + "lc" + "cl" + "yt" = "tylcclyt" ,长度为 8 。
"lcyttycl" 是另一个可以得到的最长回文串。
示例 3:
输入:words = ["cc","ll","xx"]
输出:2
解释:最长回文串是 "cc" ,长度为 2 。
"ll" 是另一个可以得到的最长回文串。"xx" 也是。
提示:
1 <= words.length <= 10^5words[i].length == 2-
解法一:哈希表
分几种情况讨论:
相同字母
- 奇数个:
- 前面如果使用过奇数个相同字母,那么这里只能使用偶数个了,最大的偶数就是减一咯
- 前面没使用过奇数个相同字母,那么这里就可以使用奇数个了
- 偶数个:可以正常使用
- 奇数个:
- 不同字母
- 存在反转的字母:取两个出现次数最小的次数算
- 不存在反转的字母:0
```go
func longestPalindrome(words []string) int {
hash := make(map[string]int)
for _, word := range words {
hash[word]++
}
res := 0
flag := 0
for word, num := range hash {
resverseWord := string(word[1]) + string(word[0])
if resverseWord == word {
} else {if num % 2 == 1 { if flag == 0 { res += num * 2 flag = num } else { res += (num -1) * 2 } } else { res += num * 2 }
}tmp := hash[resverseWord] hash[resverseWord] = 0 res += min(tmp, num) *2 * 2
}
return res
}
func max (a, b int) int { if a > b { return a } return b }
func min (a, b int) int { if a > b { return b } return a } ```
