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: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
回文必须两边对称,如果某个字符有偶数个,那么最长回文应该加上该字符个数,如果有字符不是偶数个,最长回文长度应加上该字符个数减1,最后,只要有1个字符的个数为奇数个,还可以再加1(在最长回文中放在中间位置)。那么问题的难点在于,怎么统计字符串的每个字符的个数,还是老套路,定义1个数组统计每个字符个数。
public class Solution {
public int longestPalindrome(String s) {
int[] cha=new int[52];
int len=s.length();
int flag=0;// 看是不是至少有一个字符数目是奇数个的
int sum=0;
for(int i=0;i<len;i++)
{
if(s.charAt(i)>='a') cha[s.charAt(i)-'a'+26]+=1;
else cha[s.charAt(i)-'A']+=1;
}
for(int i=0;i<52;i++)
{
if((cha[i]&0x01)==1)
{
flag=1;
sum+=cha[i]-1;
}
else sum+=cha[i];
}
return sum+flag;
}
}