题目来源【Leetcode】
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,然后判断是否有出现奇数次的,有最后结果就加一,没有就加零;
class Solution {
public:
int longestPalindrome(string s) {
int l = s.length();
int a[200] = {0};
for(int i = 0;i < l; i++) a[s[i]]++;
int count = 0;
int flag = 0;
for(int i = 64; i < 200; i++){
count += a[i]/2;
if(a[i]%2 == 1) flag = 1;
}
return count*2+flag;
}
};