3 lines in C++


  • 0
    W

    Since we know the string consists of lowercase or uppercase letters, count[0] can be used for counting odds.

    int longestPalindrome(const string &s) {
        int count[128]{};
        for (auto c : s) ++count[c];
        for (auto num : count) count[0] += num & 1;
        return s.size() - count[0] + (count[0] > 0);
    }
    

    And here is a shorter solution.

    int longestPalindrome(const string &s) {
        int count[128]{};
        for (auto c : s) count[0] += ++count[c] & 1 ? 1 : -1;
        return s.size() - count[0] + (count[0] > 0);
    }
    

Log in to reply
 

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