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.

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.

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


xufeng
8 声望3 粉丝

有多少人工就有多少智能