409. Longest Palindrome

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.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

给一组字符,返回能构成的最长的回文字符串长度。

分析:因为只需要返回长度,只需要考虑构成回文的字符元素就行。只要是成对的字符,肯定能构成回文。至多只能包含一个成单的字符。

这样只需要统计每个字符的出现次数就行。

class Solution {
public:
    int longestPalindrome(string s) {
        int res = 0;
        unordered_map<char, int> m;
        for (auto c:s) {
            m[c]++;
            if (m[c]%2==0)
                res += 2;
        }  
        return res<s.length()? res+1:res;
    }
};

 

posted @ 2017-11-29 20:56  Zzz...y  阅读(127)  评论(0编辑  收藏  举报