原题链接
原题
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note: Assume the length of given string will not exceed 1,010.
Example:
Input:"abccccdd"Output:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.
题目要求
题目叫“最长回文”,顾名思义,给定一个字符串,包含大小写字母,使用这些字母任意拼凑,找出能拼出的最长的回文字符串的长度。
解法
解法:回文字符串,其长度可能是奇数也可能是偶数。总长度为偶数时,每个字符都出现过偶数词,也就是说都是2的倍数;总长度为奇数时,会有一个中间字符,位于字符正中间,两边的其他每个字符必须满足偶数个的条件。既然是求出最长回文字符串的长度,理想情况就是为奇数个。
之前讲过,计算字符出现的次数,最直接的方法就是使用数组计算每个字符出现的次数,这里字母大小写敏感,那么就要建立稍微大点的数组,并且,计算索引的方法也稍微麻烦一点。另外,为了便于计算总长度,我们不必最后才计算长度,可以每次发现有偶数个相同字符时,就累加长度,并把该字符出现的次数清零。遍历结束后,再检查是否还有其他字符,如果有任意一个,就可以使用它作为中间字符,回文字符串长度就可以再加1了。 这里,我们可以使用Java提供的BitSet类来替代数组,完美的吻合了我们的所有需求。public class Solution { // 计算索引 private int getIndex(char ch) { return (int)ch >= 'a' ? ch - 'a' + ('Z' - 'A') : ch - 'A'; } public int longestPalindrome(String s) { int ret = 0; BitSet bs = new BitSet(26 * 2); for (int i = 0; i < s.length(); i++) { int index = getIndex(s.charAt(i)); bs.set(index, !bs.get(index)); // 如果之为false,说明取反之前是true,则这是第二次遇到该字母了,回文长度+2 if (!bs.get(index)) { ret += 2; } } // 不为空说明还有字母,可选择一个作为回文字符串的中间字符。 if (!bs.isEmpty()) { ret += 1; } return ret; } public static void main(String[] args) { Solution s = new Solution(); assert(s.longestPalindrome("abcba") == 5); assert(s.longestPalindrome("aa") == 2); assert(s.longestPalindrome("abccccdd") == 7); assert(s.longestPalindrome("Abccccdd") == 7); assert(s.longestPalindrome("a") == 1); assert(s.longestPalindrome("") == 0); }}