【Leetcode 每日一题】2131. 连接两字母单词得到的最长回文串
问题背景
给你一个字符串数组 w o r d s words words。 w o r d s words words 中每个元素都是一个包含 两个 小写英文字母的单词。
请你从 w o r d s words words 中选择一些元素并按 任意顺序 连接它们,并得到一个 尽可能长的回文串 。每个元素 至多 只能使用一次。
请你返回你能得到的最长回文串的 长度 。如果没办法得到任何一个回文串,请你返回 0 0 0。
回文串 指的是从前往后和从后往前读一样的字符串。
数据约束
- 1 ≤ w o r d s . l e n g t h ≤ 10 5 1 \le words.length \le 10 ^ 5 1≤words.length≤105
- w o r d s [ i ] . l e n g t h = 2 words[i].length = 2 words[i].length=2
- w o r d s [ i ] words[i] words[i] 仅包含小写英文字母。
解题过程
这题也是经典的分析清楚之后,代码很好写。
由于所有字符串长度都是 2 2 2,那么两个字符不同的字符串可以分布到整个字符串的两端,可选数量以对应的两种字符串中数量较少的为准。
两个字符相同的字符串如果总数为偶数,那么可以全部用上,分布到字符串两端;如果总数为奇数,那么可以用上其中的偶数个。
此外,如果存在奇数个字符相同的字符串,那么还可以放一个在字符串中间。
具体实现
class Solution {public int longestPalindrome(String[] words) {int[][] count = new int[26][26];for (String word : words) {count[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;}int res = 0;int odd = 0;for (int i = 0; i < 26; i++) {int cur = count[i][i];res += cur - cur % 2;odd |= cur % 2;for (int j = i + 1; j < 26; j++) {res += Math.min(count[i][j], count[j][i]) * 2;}}return (res + odd) * 2;}
}