美文网首页
409. Longest Palindrome 最长回文组合

409. Longest Palindrome 最长回文组合

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 10:10 被阅读0次

    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:
    7
    Explanation:
    One longest palindrome that can be built is "dccaccd", whose length is 7.
    给定只含有小写字母或大写字母的字符串,找出这些字母能组合而成的最长回文字符串的长度。
    这里认为大小写敏感,即A和a是两个不同的字符。
    注:可认为给定的字符串长度不超过1010.


    思路
    统计每个字母出现的频次,再扫描频次加入结果,偶数个字符的由于可全部加入回文组合,可直接计入最后结果,奇数个字符的由于大于1的可加入,如果有多个一个字符的则只能取其一,需设置标志,再将所有奇数字符数减1计入最后结果,再根据标志位选择最后结果是否补加1.

    class Solution {
    public:
        int longestPalindrome(string s) {
            vector<int> letterCount(52,0);
            for(auto it=s.begin();it!=s.end();it++){
                int letter=0;
                if(*it<='Z'&&*it>='A') letter=*it-'A';
                else letter=*it-'a'+26;
                letterCount[letter]++;
            }
            bool hasSingle=false;
            int res=0;
            for(auto it=letterCount.end()-1;it>=letterCount.begin();it--){
                if(*it%2==1){
                    hasSingle=true;
                    res+=(*it)-1;
                }
                else res+=(*it);
            }
            return hasSingle?res+1:res;
        }
    };
    

    相关文章

      网友评论

          本文标题:409. Longest Palindrome 最长回文组合

          本文链接:https://www.haomeiwen.com/subject/tiuhlxtx.html