给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
输入:
“abccccdd”
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindrome
分析:
首先直到回文子串的定义,从左到右和从右到左读是一样的即为回文。所以需要找到字符对的数目。如果字符对数目*2得到的数字加一或者不加一即为最终结果。这里用到哈希表记录字符个数以便统计,实际上运用数组来记录速度会快很多。
class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> charCount = new HashMap<>();
for(char c : s.toCharArray()) {
Integer freq = charCount.get(c);
charCount.put(c, freq == null ? 1 : freq + 1);
}
int count = 0;
for(Integer i : charCount.values()) {
count += (i / 2) * 2;
}
if(count < s.length()) // 如果数目小于长度就加1作为回文中间的字母
count++;
return count;
}
}