题意:给一个字符串,问用该字符串能构造出的最长的回文串的长度。
solution:hash。记录每个字母出现的次数,如果是偶数次那么全部可用,如果是奇数次那么可用n-1,如果有字母出现奇数次,那么最后的结果还需要加一。
note:c++奇数/2是下取整。还可以用int a[256]来模拟hash表,用空间换时间。
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> hash; // char-count
int res = 0;
bool odd = 0;
for ( auto i : s ) {
hash[i]++;
}
for ( auto i : hash ) {
if( i.second != 1 && i.second%2 == 0 ) { // 偶数
res += i.second;
}
else { // 奇数
res += (i.second-1);
odd = 1;
}
}
if ( odd ) {
res += 1;
}
return res;
}
};
submission: