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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章