题目来源【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;
}
};
本文介绍了一种高效算法,用于求解由给定字符串中的字符重新排列形成的最长回文序列的长度。通过统计各字符出现次数并利用这些信息计算最长回文长度。
363

被折叠的 条评论
为什么被折叠?



