4 lines C++ solution, 0ms


  • 1
    X

    The code is pretty self-explanatory: if the input string has an even length, then all the characters it is comprised of must be present there even number of times; if the input string has an odd length, then there must be exactly one character which appears there an odd number of times, all the other must appear even number of times as well.

    bool canPermutePalindrome(string s) {
        vector<int> freqs(256, 0);
        for(auto& c : s) ++freqs[c];
        auto oddCnt = count_if(freqs.begin(), freqs.end(), [](int d){return d % 2;});
        return (s.size() % 2) == oddCnt;
    }

  • 0
    S

    Can I ask the term/name for the use of "[](int d){return d % 2;}" so I can look it up? Thanks!


  • 0
    X

    It's a lambda function (introduced in C++11). Basically the idea of lambdas is to provide a concise way to write short anonymous functions in place, without bothering with implementing functor objects or creating lots of small global functions.


  • 0
    S

    Thank you so much for your explanation! Happy coding :)


Log in to reply
 

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