LeetCode Longest Palindrome

Description

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:

1
2
3
4
5
6
7
8
Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

The original problem is here.

My Solution

I solve this problem in C++, as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int longestPalindrome(string s) {
if(s.size() <= 1) {
return s.size();
}
vector<int> letters(52, 0);
int mid = 0;
int res = 0;
for(int i = 0 ; i< s.size(); i++) {
if (s[i] >= 'a') {
letters[s[i] - 'a'] ++;
} else {
letters[s[i] - 'A' + 26] ++;
}
}
int odd = 0 ;
for (int i = 0; i < 52; i++) {
if (letters[i] % 2 == 0) {
res += letters[i];
} else {
res += letters[i] - 1;
odd ++;
}
}
if (odd > 0) {
res += 1;
}
return res;
}
};

Note

To solve the problem, use a vector with length 52 for all letters to save the frequence.