cpp solution


  • 0
    Z
    #include <unordered_map>
    class Solution {
    public:
        int longestPalindrome(string s) {
            std::unordered_map<char, int> dict;
            int len = 0;
            bool odd = false;
            for (auto v: s) {
                if (dict.find(v) == dict.end()) {
                    dict.insert({v, 1});
                } else {
                    dict[v] += 1;
                }
            }
            for (auto cur = dict.begin(); cur != dict.end(); ++cur) {
                if (cur->second > 1) {
                    len += cur->second - (cur->second & 1);
                }
                if (!odd && cur->second & 1 > 0) {
                    odd = true;
                }
            }
            if (odd) {
                ++len;
            }
            return len;
        }
    };
    

Log in to reply
 

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