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.
注解:给定一个由大小写字母组成的字符创,求:用这个字符串中的字符可以组成的最长回文串
思路1:回文串特点:在一个回文串中,最多(可能没有)有一个字符出现次数为奇数次(中间字符),其它字符都为偶数次
解法:用哈希表记录每个字符出现的次数,对每个字符:出现次数为偶数,都计入总长度;出现次数为奇数,将其次数减1,成为偶数个,计入总长度
int longestPalindrome(string s) { vector<int> hash( 128, 0 ); int res = s.size(); for( char c : s ) ++hash[c]; int oddcount = 0; for( int n : hash ) { if( n % 2 != 0 ) ++oddcount; } if( oddcount != 0 ) res = res - oddcount + 1; return res; }