码迷,mamicode.com
首页 > 其他好文 > 详细

409. Longest Palindrome

时间:2017-11-29 21:59:49      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:out   who   分析   map   har   cas   字符   style   hat   

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

 

409. Longest Palindrome

标签:out   who   分析   map   har   cas   字符   style   hat   

原文地址:http://www.cnblogs.com/Zzz-y/p/7922679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!