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

letecode [409] - Longest Palindrome

时间:2019-06-21 21:02:04      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:内存   turn   letters   end   ati   nat   out   find   nsis   

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.

题目大意

  给定一个字符串,计算使用这些字符能够组成的回文串的最大长度。

理  解:

  当某个字符出现偶数次时,即可用于组成回文串,回文串中至多允许一个字符出现一次。

代 码 C++:

class Solution {
public:
    int longestPalindrome(string s) {
        set<char> m_set;
        set<char>::iterator itr;
        int count = 0;
        for(char ch:s){
            itr = m_set.find(ch);
            if(itr!=m_set.end()){
                count = count + 2;
                m_set.erase(itr);
            }else{
                m_set.insert(ch);
            }
        }
        if(!m_set.empty())
            count++;
        return count;
    }
};

运行结果:

  执行用时 :20 ms, 在所有 C++ 提交中击败了10.87%的用户

  内存消耗 :10.5 MB, 在所有 C++ 提交中击败了5.02%的用户

letecode [409] - Longest Palindrome

标签:内存   turn   letters   end   ati   nat   out   find   nsis   

原文地址:https://www.cnblogs.com/lpomeloz/p/11066792.html

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