Thursday, March 5, 2020

409. Longest Palindrome -M

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.

A:

------------挨个数, 奇数的最多有一个------------
class Solution {
public:
    int longestPalindrome(string s) {
        map<char,int> m;
        for(auto ch : s)
        {
            if(m.find(ch) == m.end())
            {
                m.insert({ch,1});
            }else{
                auto it = m.find(ch);
                it->second += 1;
            }
        }
        int odd = 0; // 0 if no odd found, 
        int res = 0;
        for(auto it = m.begin(); it!= m.end(); ++it)
        {
            int c = it->second;
            if(  (c&1) == 0)
            {
                res += c;
            }else{
                odd = 1;
                res += c-1;                
            }
        }
        return res + odd;
    }
};


Mistakes:

int c = 4;
if( c&1 == 0){
    print("a");
}else{
    print("b");
}









这里print 结果是 b






No comments:

Post a Comment