C++ without explicit loops


  • 0
    M
    class Solution {
    public:
        int longestPalindrome(const string& s)
        {
            int freq[256] = { 0 };
    
            // AKA for(char ch : s) freq[ch]++;
            for_each(
                begin(s), end(s),
                [&](char ch) { freq[ch]++;  });
    
            auto best = s.size();
    
            auto odds = count_if(
                begin(freq), end(freq),
                [](int cnt) { return cnt & 0x1; });
    
            if (1 < odds)
            {
                best -= (odds);
                best += 1;
            }
    
            return best;
        }
    };
    

Log in to reply
 

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