5 lines C++


  • 6
    class Solution {
    public:
        int longestPalindrome(string s) {
            vector<int> m(256, 0);        
            for (auto& c : s) m[c-'\0']++;
            int result = 0;
            for (auto& i : m) result += i%2 ? (result%2 ? i-1 : i) : i;
            return result;
        }
    };
    

  • 4

    Nice idea, checking result for whether we already used an odd one. Can be a bit shorter, though:

    result += i - (i & 1 & result);
    or
    result += i & ~(result & 1);
    

    How I think about the first one: We can use each letter's full count i, except when after pairing them up there's an odd extra one (i & 1) and we already used an odd extra one (& result), then we need to leave it behind.


  • 1
    S

    Excuse me, I want to ask why do you minus '\0'. ( at line 5)

    I think '\0' = 0

    Which means use m [ c ] will get the same output as m[c -'\0']


  • 1

    @vesion check result%2 for whether an odd one has been added, excellent!!


  • 2

    @storm654321 Just because my local compiler gives me a warning about the type coercion. It doesn't matter you use m[c] directly.


  • 0
    S

    @vesion Thanks! I got it. :D


Log in to reply
 

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