C++ solution using map


  • 0
    M
    class Solution {
    public:
        int longestPalindrome(string s) {
            map<char, int> my_map;
            map<char, int>::iterator my_map_it;
            for(auto c = s.begin(); c != s.end(); ++c){
                my_map_it = my_map.find(*c);
                if(my_map_it != my_map.end()){
                    (my_map_it->second)++;
                }else{
                    my_map.insert(pair<char, int>(*c, 1));
                }
            }
            
            vector<int> odd_vec;
            int ret = 0;
            for(auto it = my_map.begin(); it != my_map.end(); ++it){
                if(it->second % 2 == 0){
                    ret += it->second;
                }else{
                    odd_vec.push_back(it->second);
                }
            }
            
            if(odd_vec.size() >= 1){
                for(auto it = odd_vec.begin(); it != odd_vec.end(); ++it){
                    ret += (*it) - 1;
                }
                ret++;
            }
            
            return ret;
        }
    };
    

Log in to reply
 

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