Stupid 6ms C++ Solution


  • 0
    class Solution {
    public:
        int longestPalindrome(string s) {
            vector<int> table(52);
            // en-table all counts
            for(auto& ch: s) {
                int index;
                if (islower(ch)) {
                    index = ch - 'a';
                }else {
                    index = ch - 'A' + 26;
                }
                table[index] += 1;
            }
                    
            bool has_odd = false;
            
            int count = 0;
            
            for (int i = 0; i < table.size(); ++i) {
                if (table[i] % 2 == 0) {
                    // even counts will contribute all
                    count += table[i];
                }else {
                    if(!has_odd) has_odd = true;
                    // odd counts will give n-1 length
                    if (table[i] > 1) count += table[i] - 1;
                }    
            }
            
            return has_odd ? count + 1 : count;
        }
    };
    

Log in to reply
 

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