LeetCode刷题: 【409】 最长回文串

1. 题目

在这里插入图片描述

2. 思路

字符计数
偶数必然可用于构成回文
奇数只需-1,即可构成回文
在有奇数的情况下,最后需要+1

[aabbcaabb]

3. 代码

class Solution {
    
    
public:
    int longestPalindrome(string s) {
    
    
        // 字符计数
        unordered_map<char, int> temp;

        for(char c : s){
    
    
            temp[c]++;
        }

        // 计算可形成回文的字符数
        int ans = 0;
        bool singal = false;
        for(auto it : temp){
    
    
            // 偶数必然可构成回文
            if(it.second % 2 == 0){
    
    
                ans += it.second;
            }else{
    
     // 奇数 -1
                singal = 1;
                ans += it.second - 1;
            }
        }

        // 奇数存在:补充
        return ans + singal;
    }
};

猜你喜欢

转载自blog.csdn.net/Activity_Time/article/details/104980046