Leetcode Longest Palindrome

来源:互联网 发布:野狼工具箱软件下载 编辑:程序博客网 时间:2024/04/30 14:28

题意:给出一串字符串,求其所能组成的最大回文串。

思路:对于出现偶数次的字母,直接累加;对于出现奇数次的字母,取其次数减1。如果出现奇数次,还可再加一。

class Solution {public:    int longestPalindrome(string s) {        int re1 = 0;        vector<int> ch1(52, 0);                for(int i = 0; i < s.length(); ++ i) {            if(s[i] >= 'A' && s[i] <= 'Z') ch1[s[i] - 'A'] ++;            else ch1[s[i] - 'a' + 26] ++;        } //cout << "here";                int maxs1 = 0;        for(int i = 0; i < 52; i ++) {            if(ch1[i] % 2 == 0) re1 += ch1[i];            else {                re1 += ch1[i] - 1;                maxs1 = max(maxs1, ch1[i]);            }        }                if(maxs1) return re1 + 1;        else return re1;        //return re1 + maxs1;            }};


0 0