#1描述:输入一串字符,输出能构成回文串的最大个数:
#2思路 1、模除判奇偶,把偶数全部累加起来,奇数n时加上 n-1
2、构hash , 前一个key 可以是字符后一个value 可以是数值
#3notes:
1、undered_map<char,int>hash;
2、for ( auto a: s) 自动类型匹配auto
#4代码
# 5
时间复杂度分析:最多需要遍历输字符串中n个字符,所以时间复杂度为
O(n)
空间复杂度分析:根据unordered_map的空间复杂度为
O(n)
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char,int> hash; //构hash
for(auto x: s) hash[x]++; //统计数字
int res=0; //偶数的总个数
int center=0; //中间的那个是有还是没有
for(auto item:hash) // 又一次这种写法
{
if(item.second % 2 == 0)
res+=item.second;
else
{
res+=item.second-1;
center++; //center=1; 最后只返回一个 res + center 就好了
}
}
if(center>0)
return res+1;
else
return res;
}
};