Easy to understand C++ solution with descriptions.


  • 0
    S

    Let's count the letter first. All letters with an even count can be used in the palindrome. For all the letters with an odd count can be used in the palindrome except for one from each such letter. Finally, if we had at least one letter with an odd count, we can insert it in the middle.

    class Solution {
    public:
        int longestPalindrome(string s) {
            int alphabet[26 * 2] = {0};
            for (auto c:s){
                ++alphabet[c > 'Z'? c - 'a' + 26 : c - 'A'];
            }
            int count = 0;
            for (auto i:alphabet){
                if ((i&1)) {
                    --count;
                }
            }
            return s.size()  + (count != 0 ? count + 1 : 0);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.