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.
看了别人的答案,很多人对回文的定义不太一致。而且很繁琐。
我的solution是 accepted了,所以回文应该和题目是一致的,而且个人觉得比较简单明了。所以就我第一次上传solution分享一下。
思路:用num数组记录各字符出现的次数,偶数的记录回文长度,奇数的先减1再记录长度。设定奇数出现的标志位odd,字符串中有奇数则为1,并使最后的长度+1,否则为0。
该答案刚好考虑了各种特殊情况,也不需要区别对待大小写,大写字母小写字母中间的那些字符出现均为0次,亦不影响结果。
int longestPalindrome(char* s) {
int i=0,sum=0,odd=0;
int num[65]={0};C
for(i=0;s[i]!=NULL;i++)
num[s[i]-'A']++;
for(i=0;i<65;i++)
{
if(num[i]%2==0)
sum+=num[i];
else
{sum+=num[i]-1;
odd=1;}
}
return sum+odd;
}