[leetcode] 409. Longest Palindrome 解題報告

題目鏈接:https://leetcode.com/problems/longest-palindrome/

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

思路:對每個字符計數,如果還要做個標記是否有奇數個字符,然後對偶數的字符都可以最終組成迴文,還可以帶一個奇數字符.

代碼如下:

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char, int> hash;
        for(auto ch: s) hash[ch]++;
        int ans = 0, odd = 0;
        for(auto val: hash) 
        {
            if(val.second&1) odd = 1;
            ans += val.second & 0xfffffffe;
        }
        return ans + odd;
    }
};


發佈了425 篇原創文章 · 獲贊 40 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章