LeetCode/solutions/409. Longest Palindrome.md

1.1 KiB
Raw Blame History

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;
    }
};