This commit is contained in:
kkunkka
2025-05-25 13:24:27 +08:00
parent bed3790594
commit 628ae27ce6

View File

@@ -0,0 +1,36 @@
package com.dota.str._2131;
import java.util.HashMap;
import java.util.Map;
class Solution {
public static void main(String[] args) {
new Solution().longestPalindrome(new String[]{"em","pe","mp","ee","pp","me","ep","em","em","me"});
}
public int longestPalindrome(String[] words) {
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
var res = 0;
for (String word : words) {
if (map.get(word) == 0) {continue;}
if (word.charAt(0)==word.charAt(1) && map.get(word)==1) continue;
var s = ("" + word.charAt(1)) + word.charAt(0);
if (map.getOrDefault(s, 0) > 0) {
res += 4;
map.put(s, map.get(s) - 1);
map.put(word, map.get(word) - 1);
}
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 0) {
var s = entry.getKey();
if (s.charAt(0) == s.charAt(1)) {
return res + 2;
}
}
}
return res;
}
}