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%的用户