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

相关文章
相关标签/搜索