leetcode 409. Longest Palindrome

Description

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

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

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

Example:索引

Input:
"abccccdd"ip

Output:
7leetcode

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

My solution

  • 最初理解錯了題意, 忽略了奇數字母能夠只用部分(好比個數爲5,能夠只用4個).
  • 注意 it->second & 0x1==0 的錯誤
  • 代碼註釋掉的部分是經過索引方式, 但並不是全部container均可以索引, 因此仍是習慣iterator的方式吧.
  • 此題而言, 我採用的是累加全部有用字母數目, 下面discuss方式爲去掉多餘字母, 方法更巧妙.
class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char, int> mp;
        int sum = 0;
        bool containOdd = false;
        //        for (int i = 0; i < s.size(); i++) mp[s[i]]++;
        for (auto it = s.cbegin(); it != s.cend(); it++) mp[*it]++;
        for (auto it = mp.cbegin(); it != mp.cend(); it++)
            if (it->second & 0x1) {
                sum += it->second - 1;
                containOdd = true;
            } else sum += it->second;
        return sum + containOdd;
    }
};

Discuss

int longestPalindrome(string s) {
    vector<int> count(256);
    for (char c : s)
        ++count[c];
    int odds = 0;
    for (int c : count)
        odds += c & 1;
    return s.size() - odds + (odds > 0);
}
  • +(odds > 0) 完成的邏輯是:若是存在奇數的字母, 則最總體可爲奇數的迴文, 不存在奇數則不進行修正.
  • 每有一個奇數, 就在s.size()減去1, 這個思路很不錯

Reference

相關文章
相關標籤/搜索