LeetCode贪心 最长回文串

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome here.

思路
首先学习一个新单词,palindrome回文。
主要思路是哈希表+贪心,随后对哈希表进行遍历。当元素值是奇数时,需要用一个flag记录一下出现过奇数的,sum累加上奇数值-1(因为当有多个奇数出现时,不可能直接拼接成一个回文串);当元素是偶数时,sum直接累加上偶数值。在循环结束后,若flag为true,表明组成的回文串中有出现奇数次数的字母,因此sum需要再加上1。

代码

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char, int> letter_map;
        for(auto c : s)
        {
            letter_map[c]++;
        }

        int sum = 0, temp;
        bool flag = false;
        for(auto it : letter_map)
        {
            temp = it.second;
            if(temp % 2 == 1)
            {
                sum += temp - 1;
                flag = true;
            }
            else 
            {
                sum += temp;
            }
        }
        if(flag == true)
        sum += 1;

        return sum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值