mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
1.1 KiB
1.1 KiB
409. Longest Palindrome
思路
给出一些包含大小写的字母,判断能由这些字母组成的回文串最长为多少。
分析:如果某个字母出现次数为偶数,那肯定全部都能放进目标最长的回文串,如果某个字母出现次数为奇数,则只能放下不超过这个奇数的最大偶数(也就是减1)个该字母。
不过需要注意的是,如果出现了出现次数为奇数的字母,则最后的回文串长度按照上诉思路计算后还应该加1,此时回文串长度为奇数,例如dccaccd。
时间复杂度O(n), 空间复杂度O(1)
C++
class Solution {
public:
int longestPalindrome(string s) {
vector<int>count(52, 0);
for(int i = 0; i < s.size(); i++){
if(s[i] >= 'a' && s[i] <= 'z') count[s[i] - 'a']++;
else count[s[i] - 'A' + 26]++;
}
int odd_tag = 0, res = 0;
for(int n: count){
if(n % 2 == 1) odd_tag = 1;
res += (n - n % 2);
}
res += odd_tag;
return res;
}
};