判回文串字符数

#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;
    }
};

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值