C++ 3ms, easy to understand


  • 0
    class Solution {
    public:
        int increment(int ary[], int i, bool& odd)
    {
        if (ary[i]%2 == 0)
            return ary[i];
        else
        {
            odd = true;
            return ary[i]/2 * 2;
        }
    }
    
    int longestPalindrome(string s) {
        int length = 0;
        bool odd = false;
        int lower[26],upper[26];
        for (int i = 0;i<26;++i)
        {
            lower[i] = 0;
            upper[i] = 0;
        }
        for (int k = 0;k<s.size();++k)
        {
            if (s[k] >= 97) // ascii for 'a'
                lower[s[k]-'a']++;
            else
                upper[s[k]-'A']++;
        }
        
        for (int i = 0;i<26;++i)
        {
            length += increment(lower, i, odd);
            length += increment(upper, i, odd);
        }
        if (odd)
            return length + 1;
        else
            return length;
    }
    };
    

Log in to reply
 

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