[C++] Concise Solution Explained, 100% Time, ~99% Space
Okay, this is a nice, simple one: first of all we build our own usual frequency map, then we go through it, taking each frequency and rounding it down to the ne
Okay, this is a nice, simple one: first of all we build our own usual frequency map, then we go through it, taking each frequency and rounding it down to the next multiple of `2` before adding it to our accumulator variable `res`.\n\nNotice that I did it with bitwise operators just to show off, but `res += e.second >> 1 << 1;` is just equivalent to writing `res += e.second / 2 * 2;` in this case.\n\nOnce I am done, I finally check if the final sum is equal to the length of the original string or not, no need to check with a lot of characters. If it is not, it means I can just take one character to put in the middle to have an even longer palindrome.\n\nThe code I wrote 9 months ago:\n\n```cpp\nclass Solution {\npublic:\n    int longestPalindrome(string s) {\n        // res created, frequency map created and populated\n        int res = 0;\n        std::unordered_map<char, int> f;\n        for (auto c: s) f[c]++;\n        for (auto e: f) {\n            // I take the frequence and round it down to the next multiple of 2\n            res += e.second >> 1 << 1;\n        }\n        // if i did not use all the available characters, then the max lenght is + 1\n        return res + (res != s.size());\n    }\n};\n```\n\nThe code as I updated it today, with only minor changes in order for it to work with a frequency array instead - much faster and efficient:\n\n```cpp\nclass Solution {\npublic:\n    int longestPalindrome(string s) {\n        // res created, frequency array initialised and populated\n        int res = 0;\n        int f[52];\n        for (auto &e: f) e = 0;\n        for (auto c: s) f[c < \'a\' ? c - \'A\' : c - \'a\' + 26]++;\n        for (auto e: f) {\n            // I take the frequence and round it down to the next multiple of 2\n            res += e >> 1 << 1;\n        }\n        // if i did not use all the available characters, then the max lenght is + 1\n        return res + (res != s.size());\n    }\n};\n```
['C', 'Counting', 'C++']