409. Longest Palindrome

来源:互联网 发布:java上传txt文件 编辑:程序博客网 时间:2024/06/13 07:54
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.

Subscribe to see which companies asked this question.




#include <iostream>
#include <string>
using namespace std;


class Solution {
public:
    int longestPalindrome(string s) {
    int times[52]={0};
        for(int i=0;i<s.length();i++)
        {
        if(s[i] >= 'A' && s[i] <= 'Z')
        {
        int n = s[i]-'A';
        times[n]++;
}
else if(s[i] >= 'a' && s[i] <= 'z')
{
int n = s[i]-'a'+26;
times[n]++;
}
}

int count = 0;
int max = 0;
int index = 0;
for(int i=0;i<52;i++)
{
if(times[i] == 0)
count+=0;
else if(times[i]%2 == 0)
count+=times[i];
else
{
max = times[i];
index = i;
// cout << i << " " << index << endl;
count = count + times[index];
break;
}
// cout << count << endl;

}

if(index == 0 && max == 0)
return count;

else
{

for(int j=index+1;j<52;j++)
{
if(times[j] == 0)
count+=0;
else if(times[j]%2 == 0)
count+=times[j];
else
{
if(times[j] > max)
{
max = times[j];
count--;
count+=times[j];
}
else
{
times[j]--;
count+=times[j];
}
}
// cout << count << endl;
}

return count;
}
    }
};

0 0